spring整合junit
阿新 • • 發佈:2020-07-25
在平常junit單元測試中,junit不能識別spring的註解,從而我們無法使用注入的方式獲得ioc容器中的物件。
解決:spring整合junit,用spring提供的執行器,在執行測試方法前讀取配置檔案(或註解)來建立容器,在執行測試方法。
步驟:
1.新增依賴spring-test
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>5.0.2.RELEASE</version> </dependency>
2.在測試類上新增@RunWith 註解,指定 Spring 的執行器,這裡 Spring的執行器是SpringJunit4ClassRunner
@RunWith(SpringJUnit4ClassRunner.class)
3.在測試類上新增@ContextConfiguration註解,通過註解裡邊的屬性locations指定spring配置檔案的位置
@ContextConfiguration(locations = {"classpath:ApplicationContext.xml"})
4.注入物件,執行測試
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath:ApplicationContext.xml"}) public class MybatisTest { @Autowired private UserMapper userMapper; @Test public void testFindAll(){ List<User> list = userMapper.findAll(); for (User user : list) { System.out.println(user); } } }