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