spring test + junit + mockito实现单元测试

对Service层进行单元测试

只需要引入Junit4和Mockito的依赖

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bytedance.catering.dal.db.mapper.SupplierMapper;
import com.google.common.collect.Lists;
import org.assertj.core.util.Maps;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.DisplayName;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;

import java.util.List;
import java.util.Map;

import static org.junit.Assert.*;
import static org.mockito.Mockito.*;

@RunWith(MockitoJUnitRunner.class)

@InjectMocks用来表明要单测的service
@Mock表明哪个类要被注入待单测service

    @InjectMocks
    private SupplierServiceImpl supplierServiceImpl;
    @Mock
    private SupplierMapper supplierMapper;

mockito用法:链接

对Controller层进行单元测试

import org.junit.jupiter.api.TestInstance;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.context.WebApplicationContext;
@TestInstance(TestInstance.Lifecycle.PER_CLASS)

构造出用于模拟请求发送的mvc

protected MockMvc mockMvc;
MockitoAnnotations.initMocks(this);
        this.mockMvc = MockMvcBuilders.standaloneSetup(applyDataDetailController).build();

构造请求

@DisplayName("我的申请列表")
@Test
void getMyApply() throws Exception {
        Mockito.when(applyTaskListBizService.getMyApplyList(myApplyTaskListDTO))
                .thenReturn(myApplyListVO);
        MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders
                .post(URL_PREFIX + "getMyApply")
                .contentType(MediaType.APPLICATION_JSON_UTF8)
                .characterEncoding(ENCODE)
                .content(JsonUtils.toJsonString(myApplyRequest)))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andDo(MockMvcResultHandlers.print())
                .andReturn();
        String contentAsString = mvcResult.getResponse().getContentAsString();
        Assertions.assertEquals(JsonUtils.toJsonString(myApplyResponse), contentAsString);
    }
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值