Java ------ Spring框架 借助 @Test 注解测试

将之间的测试,改成使用 @test 进行测试

1、在spring中使用test 注解需要借助 junit-4.12.jar和hamcrest-all-1.3.jar 两个jar 包

导包办法:右键 project->properties->java build path->libaries->add external jars 

2、 将之前的

public class SpringTest {
    public static void main(String[] args) {
        //获取 配置文件
        ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"applicationContext.xml"});
        //获取bean 对象    
        StudentService stuser = (StudentService)context.getBean("ser_stu");
        stuser.addStudent();
    }

}

变成

//声明这是spring 的测试类
@RunWith(SpringJUnit4ClassRunner.class)
//定位spring 的配置文件
@ContextConfiguration("classpath:applicationContext.xml")
public class SpringTest {
    //给测试类装配对象
    @Autowired
    StudentService serStu;
    
    @Test
    public void test1() {
        serStu.addStudent();        
    }
    
}

运行一下

 多个测试方法也可以,不同部分不相互影响

原文地址:https://www.cnblogs.com/obge/p/14663526.html