原址:点击打开链接
Junit 单元测试能够很轻易的对单个类进行测试,相对于在每个类中增加了一个main方法,它是一种无状态或者状态确定的单元测试,对于测试含有大量的复杂的类之间有依赖关系的测试,还是比较麻烦,而spring mvc提供了大量类之间的管理,使类之间的关系完全透明化,显然,如果junit4 能够支持spring mvc的单元测试,那么无疑给开发带来了效率的极大提高。目前junit4 能够不但能够支持spring ioc的单元测试还能够支持spring mvc的测试。
2. 待测试的类:<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-core</artifactId> <version>1.9.5</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>3.2.3.RELEASE</version> <scope>test</scope> </dependency>
3. xml配置package com.spring.test
public class Student { private Integer age; private String name; public Student(Integer age, String name) { super(); this.age = age; this.name = name; } @Override public String toString() { return "Student [age=" + age + ", name=" + name + "]"; } }
<bean id ="student" name="student" class="com.spring.test.Student"> <constructor-arg index="0" value="20"/> <constructor-arg index="1" value="fang"/> </bean>
此时,package com.spring.test; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.web.context.WebApplicationContext; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { // "classpath:/META-INF/spring/applicationContext.xml", "classpath:/META-INF/spring/BsConfig.xml" // "file:src/main/webapp/WEB-INF/spring/webmvc-config.xml"
}) @WebAppConfiguration public class StudentTest { @Autowired private Student student; @Autowired private ApplicationContext aC; @Test public void test() { System.out.println("display student: " + student.toString()); } @Test public void testApplication() { Student student = (Student) aC.getBean("student"); System.out .println("application display student: " + student.toString()); } }
})
@Autowired即可完成调用.private Student student;
@Test public void test() { System.out.println("display student: " + student.toString()); }
@Testpublic void testApplication () {Student student = ( Student ) aC . getBean ( "student" );System . out. println ( "application display student: " + student . toString ());}