Spring 使用Junit的MockMvc 写测试用例

本文详细介绍了如何使用MockMvc进行Spring测试用例的编写,包括配置文件设置、pom.xml所需依赖、测试类的构建以及执行请求、断言、结果处理等关键步骤。同时,文中也提及了在配置文件位置不同时的注意事项,强调MockMvc能模拟前端请求,测试Spring MVC的完整流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

怕以后忘掉,随便写写

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();
    }
}

1、mockMvc.perform执行一个请求;

2、MockMvcRequestBuilders.get("/user/1")构造一个请求

3、ResultActions.andExpect添加执行完成后的断言

4、ResultActions.andDo添加一个结果处理器,表示要对结果做点什么事情,比如此处使用MockMvcResultHandlers.print()输出整个响应结果信息。

5、ResultActions.andReturn表示执行完成后返回相应的结果。


4、其中可能遇到的坑:


1)、如果spring的配置文件在默认的目录下,使用@ContextConfiguration(locations = "classpath:spring-config.xml")即可


但是!如果spring的配置文件在WEB-INF目录下,请使用

@ContextConfiguration(locations={"file:src/main/webapp/WEB-INF/spring-config.xml"})

否则会找不到配置文件


说到这里可以提一下为什么需要加载配置文件,使用mockMvc,会创建整套完整流程,模拟从前端发出的请求,个人理解为使用这种方法调用controller和前端、postman等调用controller没什么区别,这样可以测试完整的Spring MVC流程,即从URL请求到控制器处理,再到视图渲染都可以测试。


2)、执行用例时报这种异常

java.lang.NoSuchMethodError: com.jayway.jsonpath.JsonPath.compile(Ljava/lang/String;[Lcom/jayway/jsonpath/Filter;)Lcom/jayway/jsonpath/JsonPath;

解决方法:
这个异常实在蛋疼,自己感觉一切正常,但是用例就是报异常,后来查了一下,发现了这个解决方法
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>0.8.1</version>
<scope>test</scope>
</dependency>


尝试将json-path的版本降低,或者重新加载maven的依赖

刚刚接触,有错误的地方还请各位大牛指出






评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值