spring下的junit測試

今天的學習中遇到一個問題,測試spring+mybaits時單獨使用junit測試,導致不成功,userService一直空指針。

經排查,最後引入了spring-test的包,並且加入瞭如下代碼就可以了。

test

@RunWith(SpringJUnit4ClassRunner.class) // 整合
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
public class Test{
    @Resource
    private UserService userService=null;
@org.junit.Test
    public void test(){
        User user=userService.getByUserName("jack");
        System.out.println("name:"+user.getUserName());
    }
}
pom中引入spring-test

<!--junit-->
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.11</version>
    <!-- 表示開發的時候引入,發佈的時候不會加載此包 -->
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>${spring.version}</version>
</dependency>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章