今天的學習中遇到一個問題,測試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>