Day22 Spring test模組

信仰G發表於2020-10-17

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>
	<!--spring整合junit需要用4.12及以上的包-->
	<dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
	</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);
    }
}

相關文章