SpringMvc使用junit、MockMvc测试controller 简单用例

1.引入依赖

<dependency>
	<groupId>junit</groupId>
	<artifactId>junit</artifactId>
	<version>4.12</version>
</dependency>
<dependency>  
     <groupId>org.springframework</groupId>  
     <artifactId>spring-test</artifactId>  
     <version>4.3.6.RELEASE</version>
     <scope>test</scope>  
</dependency>  

2.需要测试controller

	/**
	 * junit测试
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/junit",produces={"application/json; charset=UTF-8"})
	@ResponseBody
	public Result junit(HttpServletRequest request) {
		
		return Result.success();
		
	}	

3.封装baseTest,需要测试的controller继承这个类即可

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations = { "classpath:/*.xml" })
@ComponentScan(basePackages = { "com.cmedicine.core.action" })
//当然 你可以声明一个事务管理 每个单元测试都进行事务回滚 无论成功与否
//@TransactionConfiguration( transactionManager = "transactionManager",defaultRollback = true)
//@Transactional
public class BaseTest<T> {
	public Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private WebApplicationContext wac;

	protected MockMvc mockMvc;

	protected MockHttpServletRequest request;
	protected MockHttpServletResponse response;

	/**
	 * 初始化SpringmvcController类测试环境
	 */
	@Before
	public void setup() {
		// 实例化方式一
//	     mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();

		// 实例化方式二
		mockMvc = MockMvcBuilders.standaloneSetup(getT()).build();
	}

	/**
	 * 根据泛型实例化
	 * @return
	 */
	private T getT() {
		Type genericSuperclass = this.getClass().getGenericSuperclass();
		// 获取类型第一个泛型参数
		ParameterizedType parameterizedType = (ParameterizedType) genericSuperclass;
		Class<T> modelClass = (Class<T>) parameterizedType.getActualTypeArguments()[0];
		T Object = null;
		try {
			Object = modelClass.newInstance();
		} catch (InstantiationException | IllegalAccessException e) {
			e.printStackTrace();
			System.out.println("模型构造失败...");
		}
		return Object;
	}
}

4.测试类

public class TestActionTest extends BaseTest<TestAction> {

	@Test
	public void testJunit() {
	     try {
	    	 	ResultActions resultActions = mockMvc
	    	 			.perform(MockMvcRequestBuilders.get("/test.do/junit"));
	            MvcResult mvcResult = resultActions
	            		.andDo(MockMvcResultHandlers.print())
	            		.andExpect(MockMvcResultMatchers.status().isOk())
	            		.andReturn();
			String result = mvcResult.getResponse().getContentAsString();
			System.out.println("==========结果为:==========\n" + result + "\n");
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	}

}

5.运行junit Test

可以看到我们测试成功了

发布了9 篇原创文章 · 获赞 2 · 访问量 2844
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览