在demo-service層集成junit並實例測試。java
引入spring-test,junit中jarspring
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>4.2.3.RELEASE</version> <scope>test</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency>
classpath*:表示加載其餘jar中配置文件(即demo-data中mybatis相關配置)。express
package base; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration({"classpath*:spring-*.xml", "classpath*:mybatis/mybatis-*.xml"}) public class BaseJunitTest { }
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd "> <!--spring ioc中掃描-註解Service掃入--> <context:component-scan base-package="com.company"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Service"/> </context:component-scan> </beans>
package service; import base.BaseJunitTest; import com.company.data.model.User; import com.company.service.UserService; import org.junit.Assert; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; public class UserServiceTest extends BaseJunitTest { @Autowired private UserService userService; @Test public void test(){ User user = userService.qryUserById(1L); Assert.assertTrue(user != null); } }
在要執行方法體上,鼠標右擊選擇Runspring-mvc