怕以后忘掉,随便写写
1、spring配置文件
该声明为bean的类就声明,测试之前项目要能运行,所以spring的配置文件问题就不多说了,下面的数据库配置和测试类中负责回滚的TransactionalConfigration注解有关,所以贴出来。
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="mysqlDataSource" />
</bean>
2、pom.xml需要使用的包:
<!-- TEST -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
<exclusions>
<exclusion>
<artifactId>hamcrest-core</artifactId>
<groupId>org.hamcrest</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>3.2.8.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-all</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>1.9.5</version>
<scope>test</scope>
<exclusions>
<exclusion>
<artifactId>hamcrest-core</artifactId>
<groupId>org.hamcrest</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>0.8.1</version>
<scope>test</scope>
</dependency>
3、测试类
最好在源码平行目录下新建一个测试用的文件夹以及包等
@RunWith(SpringJUnit4ClassRunner.class)
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)//保证每次测试类执行完后数据库进行回滚,防止测试时产生脏数据
@Transactional
@WebAppConfiguration(value = "mydemo/src/main/webapp")
@ContextConfiguration(locations={"file:src/main/webapp/WEB-INF/spring-config.xml"})//如果spring的配置文件放在WEB-INF目录下,需要使用这种方法
@ActiveProfiles("dev")
public class demoTest {
@Autowired
WebApplicationContext wac;
private MockMvc mockMvc;
@Before
public void setUp() {
mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
}
@Test
public void getDemoidTest1() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/config/getDemo?demoid=1005"))
.andDo(MockMvcResultHandlers.print())
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.code").value(20000))
.andExpect(jsonPath("$.demoList").exists())
.andDo(MockMvcResultHandlers.print())
.andReturn();
}
}