很多朋友不是很重视单元测试,最近看了Alibaba的JAVA开发手册,认识到单元测试的重要性,与大家共勉。

       简单来说就是在我们增加或者改动一些代码以后对所有逻辑的一个检测,尤其是在我们后期修改后(不论是增加新功能,修改bug),都可以做到重新测试的工作。以减少我们在发布的时候出现更过甚至是出现之前解决了的问题再次重现。

1.生成Service层的测试类。选择方法名,右键单击-Go To - Test 利用Idea自动生成测试类

创建好后的测试类与主程序的包路径是一一对应

主要测试返回的值是否一致

Springboot 单元测试

Springboot 单元测试



assertEquals 
  函数原型1:assertEquals([String message],expected,actual) 
参数说明: 
message是个可选的消息,假如提供,将会在发生错误时报告这个消息。 
  expected是期望值,通常都是用户指定的内容。 
actual是被测试的代码返回的实际值。 


正确时返回

> 2018-02-22 14:53:59,033  [SpringManagedTransaction]- JDBC Connection [ConnectionID:1 ClientConnectionId: a48ad0bf-0c5f-4a94-adb7-f842daa93085] will not be managed by Spring

> 2018-02-22 14:53:59,038  [selectAll]- ==>  Preparing: select productid, productname from Kxxxxx
> 2018-02-22 14:53:59,065  [selectAll]- ==> Parameters:
> 2018-02-22 14:53:59,185  [selectAll]- <==      Total: 88
> 2018-02-22 14:53:59,210  [SqlSessionUtils]- Closing non transactional SqlSession [[email protected]]
> 2018-02-22 14:53:59,210  [DataSourceUtils]- Returning JDBC Connection to DataSource

单元测试


错误是返回

Springboot 单元测试

2.Controller 层

主要测试返回的状态码 是否成功

1、通过MockMvcBuilders获取MockMvc对象

2、通过MockMvc执行请求,获取ResultActions对象

MockMvcRequestBuilders主要方法:

MockHttpServletRequestBuilder get(String urlTemplate, Object... urlVariables):根据uri模板和uri变量值得到一个GET请求方式的MockHttpServletRequestBuilder;如get("/user/{id}", 1);

MockHttpServletRequestBuilder post(String urlTemplate, Object... urlVariables):同get类似,但是是POST方法;

MvcResult

即执行完控制器后得到的整个结果,并不仅仅是返回值,包含了测试时需要的所有信息,如:

MockHttpServletRequest getRequest():得到执行的请求;
MockHttpServletResponse getResponse():得到执行后的响应;
Object getHandler():得到执行的处理器,一般就是控制器;
HandlerInterceptor[] getInterceptors():得到对处理器进行拦截的拦截器;
ModelAndView getModelAndView():得到执行后的ModelAndView;
Exception getResolvedException():得到HandlerExceptionResolver解析后的异常;
FlashMap getFlashMap():得到FlashMap;
Object getAsyncResult()/Object getAsyncResult(long timeout):得到异步执行的结果;

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class KProductInfoControllerTest {
    @Autowired
    protected WebApplicationContext wac;

    protected MockMvc mockMvc;

    @Before
    public void init()
    {
        mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
    }

    @Test
    public void testShow() throws Exception
    {
        ResultActions result = mockMvc.perform(MockMvcRequestBuilders.get("/kproductinfo/"))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andDo(MockMvcResultHandlers.print());
        Assert.assertEquals(result.andReturn().getResponse().getContentAsString(),"{productname}");
    }


}


idea执行所有单元测试的设置

Springboot 单元测试

注意这句话 加上  防止中文乱码

-Dfile.encoding=UTF-8

在Configuration选项卡,用户可以选择需要运行的测试。例如,您可以从一个类、程序包、测试套件或甚至模式中运行所有的测试。这里的Fork模式让用户在一个单独的进程运行每个测试。

相关文章:

  • 2021-05-30
猜你喜欢
  • 2021-08-14
  • 2021-06-30
  • 2021-10-01
相关资源
相似解决方案