參考鏈接:https://blog.csdn.net/bestfeng1020/article/details/70145433
用Spring管理的項目,在不啟動服務的情況下進行測試類測試:@RunWith @ContextConfiguration
Demo如下:
@RunWIth(SpringJunit4ClassRunner.class) @ContextConfiguration(locations = {"classpath:applicationContext.xml"} public class MyTest{ @Test public void runBy(){ //....... } }
Spring常用的 Bean對象 如Service Dao Action等等 在我們正常的項目運行中由於有Tomcat幫我們自動獲得並初始化了這些Bean,所以我們不需要關系如何手動初始化他們。
但是在需要有測試類的時候,是沒有tomcat幫我們初始化它們的,這時候如果是下面這樣就拋出空指針異常,因為我們並沒有得到一個實例化的Bean
public class MyTest{ @Resource private StudentService studentService ; @Test public void runBy(){ //拋出空指針異常。這里的studentService 為空,並沒有被初始化Bean對象 studentService.study(); } }
所以這里需要加上@RunWith @ContextConfiguration這兩個注解
@RunWith
@RunWith就是一個運行器
@RunWith(JUnit4.class)就是指用JUnit4來運行
@RunWith(SpringJUnit4ClassRunner.class),讓測試運行於Spring測試環境
@ContextConfiguration
@ContextConfiguration Spring整合JUnit4測試時,使用注解引入多個配置文件
單個文件
@ContextConfiguration(Locations=”../applicationContext.xml”)
@ContextConfiguration(classes = SimpleConfiguration.class)
多個文件時,可用{}
@ContextConfiguration(locations = { “classpath*:/spring1.xml”, “classpath*:/spring2.xml” })