java spring项目的controller层的代码怎么用junit写单元测试用例

java spring项目的controller层的代码怎么用junit写单元测试用例。我用百度的方法不知道为什么进不去项目,不知道怎么搞,一运行就是说是一个空测试。

springboot与Junit有整合的方式,你可以模拟http请求从你的测试类发送请求到Controller,就像https://www.youyanpai.com/2018/springboot-test-with-junit4.html中描述的一样。下面我列出部分代码:

package com.youyanpai;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class SimpleTest {

private MockMvc mockMvc;
    @Autowired
     private WebApplicationContext webApplicationContext;
    /**
 * 前置处理
 * @author 有言派
 * @author www.youyanpai.com
 */
@Before
    public void before() throws Exception {
        mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
    }
/**
 * 测试方法
 * @author 有言派
 * @author www.youyanpai.com
 */
@Test
    public void testYourMethod() throws Exception {
        MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/login")
           .param("username", "youyanpai.com")
           .param("password", "youyanpai.com")
           .session(session))
           .andReturn();                
       int status = mvcResult.getResponse().getStatus();
      String responseString = mvcResult.getResponse().getContentAsString();                //请求是否正确
      Assert.assertEquals("请求错误", 200, status);                
      //输出返回值
      System.out.println("有言派提示您,测试返回结果:"+responseString);
    }
}

希望能够帮到你!

温馨提示:答案为网友推荐,仅供参考
第1个回答  2018-07-19

Spring项目controller 是依赖springmvc的

直接启动测试,是没有初始化spring容器(web.xml中初始化)的

如果是dao层 service层的测试可以用单元测试,controller层建议还是 启动web项目吧

补充一下Java WEB开发基础知识

本回答被网友采纳
第2个回答  2018-07-19
使用spring test加Mockito框架。需要添加第三方jar包
相似回答