Junit寫法及與spring整合過程詳解
阿新 • • 發佈:2020-06-21
junit之前的寫法:
//在Before中注入service類 private IUserService userService; @Before public void setUp() throws Exception { //使用xml的方式 ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); //使用註解的方式 ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfiguration.class); userService = applicationContext.getBean(IUserService.class); }
Spring與junit整合:
不需要手動建立Spring容器,自動把bean注入到測試類
1、匯入spring-test的依賴,需要junit
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>4.3.3.RELEASE</version> </dependency>
2、在測試類使用spring-test的註解
@RunWith(class)
@ContextConfiguration(指定配置檔案)
//測試類執行的環境,在spring環境下執行,在測試類,注入Spring容器的bean @RunWith(SpringJUnit4ClassRunner.class) //在建立spring容器時,指定載入哪個配置檔案 - - 相當於之前的手動獲取物件 @ContextConfiguration("classpath:applicationContext.xml") public class UserServiceImplTest { @Autowired //注入IUserService private IUserService userService; @Test public void testFindUserById() { userService.findUserById(2); }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。