Spring框架提供了测试工具spring-test
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
spring-test可以结合JUnit很轻松的进行单元测试
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class SpringDemoTest {
...
}
spring单元测试的一个简单的示例
application-xxx.xml
<context:component-scan base-package="com.faw_qm.cloud.platform.*.service"/>
DemoService.java
@Service
public class DemoService {
public String method() {
return "This is a spring test method.";
}
}
SpringDemoTest.java
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"/applicationContext-service.xml"})
public class SpringDemoTest {
@Autowired
private DemoService demoService;
@Test
public void method() throws Exception {
Assume.assumeNotNull(demoService);
String result = demoService.method();
Assert.assertEquals(result, "This is a spring test method.");
}
}