Spring和junit的整合

  • (1)在spring框架下,如何给类做单元测试?
    》Junit+手动创建IOC容器
    》Junit+spring test + 自动创建IOC容器+自动注入(不用调用getBean)
  • (2)什么是spring-test模块?
    spring提供的基于junit的测试模块,可以简化​​​IOC创建,且可以使用注入​
  • (3)如何使用Spring-test模块?
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class XxxTest

pom.xml

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.2.9.RELEASE</version>
</dependency>

TestPersonServiceSpring

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class TestPersonServiceSpring {
@Autowired
IPersonService personService;

@Autowired
@Qualifier("personDaoImpl")
IPersonDao personDao;
@Test
public void test01(){
System.out.println(personService);
//调了一个login
Person person = new Person();
boolean flag = personService.login(person);
System.out.println(flag);
}

@Test
public void test02(){
Person person = new Person();
boolean f = personDao.findByUserNameAndPassword(person);
System.out.println(f);
}
}
  • 注意要求junit的版本最少在4.12及以上。