junit 5 + mockito 编写单元测试
最近在学习过程中,涉及到了单元测试的小情况,一下就是单元测试的各个层之间的单元测试,一开始只用junit5做测试,后面发现测试的用例涉及到了数据库,不方便合作开发,故此引进mockito如有不当之处,欢迎指正:.
dao层:
@ExtendWith(SpringExtension.class)
@SpringBootTest
class OrganizationMapperTest {
@Mock OrganizationMapper organizationMapper ;
@BeforeEach
public void setUp() {
MockitoAnnotations.openMocks(this);
}
@Test
void findByNameIsNoExist() {
String name = "12345";
doThrow(new RuntimeException("数据不存在")).when(organizationMapper ).findByName(name);
try {
organizationMapper .findByName(name);
} catch (RuntimeException e) {
assertTrue(e.getMessage().contains("数据不存在"));
}
}
}
service层
@ExtendWith(SpringExtension.class)
@SpringBootTest
class OrganizationServiceImplTest {
@Mock OrganizationCreate organizationCreate;
@InjectMocks private OrganizationServiceImpl organizationServiceImpl;
@BeforeEach
public void setUp() {
MockitoAnnotations.openMocks(this);
}
@Test
void isExist() {
OrganizationCreateDto organizationCreateDto = new OrganizationCreateDto();
organizationCreateDto.setName("2555");
organizationCreateDto.setParentName("zhang");
doThrow(new IllegalArgumentException("参数异常,名称重复"))
.when(create)
.aa(aa);
try {
organizationServiceImpl.createOrganization(aa);
} catch (IllegalArgumentException e) {
assertTrue(e.getMessage().contains("参数异常,名称重复"));
}
}
@SpringBootTest(classes = {Application.class})
@AutoConfigureMockMvc
class OrganizationControllerTest {
@Resource private MockMvc mockMvc;
@InjectMocks private OrganizationController organizationController;
@Mock private OrganizationServiceImpl organizationService;
@BeforeEach
public void setup() {
// 执行以后,service自动注入到controller中。
MockitoAnnotations.openMocks(this);
// (1)构建mvc环境
mockMvc = MockMvcBuilders.standaloneSetup(organizationController).build();
}
@BeforeEach
void start() {
System.out.println("================================测试开始==================================");
}
@AfterEach
void end() {
System.out.println("================================测试结束==================================");
}
/* @Test()
@DisplayName("")
void createSuccess() throws Exception {
OrganizationCreateDto organizationCreateDto = new OrganizationCreateDto();
organizationCreateDto.setName("lisi");
organizationCreateDto.setParentName("zhang1111111");
OrganizationCreateCmd organizationCreateCmd = new OrganizationCreateCmd();
organizationCreateCmd.setOrganization(organizationCreateDto);
doThrow(new IllegalArgumentException("参数错误"))
.when(organizationService)
.createOrganization(organizationCreateCmd);
String res =
mockMvc
.perform(
post("/organization")
.content(JSON.toJSONString(organizationCreateCmd)) // RequestBody信息
.contentType(MediaType.APPLICATION_JSON))
.andDo(print()) // 打印出请求和相应的内容
.andExpect(status().isInternalServerError()) // 返回的状态是200
.andReturn()
.getResponse()
.getContentAsString(); // 返回MvcResult并且转为字符串
}*/
@Test
@DisplayName("查询成功测试")
void organizationsSuccess() throws Exception {
OrganizationList organizationList = new OrganizationList();
organizationList.setParentName("");
organizationList.setName("zhang");
List<OrganizationList> organizationLists = new ArrayList<>(10);
organizationLists.add(0, organizationList);
Mockito.when(
organizationService.pageList(
new OrganizationListByCondQry(java.util.Optional.of("zhang")),
new PageCondCo(1, 20)))
.thenReturn(new SliceRespVo<OrganizationList>(1, 20, organizationLists));
String result =
mockMvc
.perform(
get("/organization/organizations")
.param("nameLike", "zhang")
.param("num", "1")
.param("size", "20"))
.andExpect(status().isOk()) // 返回的状态是200
.andDo(print()) // 打印出请求和相应的内容
.andReturn()
.getResponse()
.getContentAsString(); // 将相应的数据转换为字符串
System.out.println(new SliceRespVo<OrganizationList>(1, 20, organizationLists));
System.out.println("--------返回的json = " + result);
}
}