如何编写测试抽象类以避免junit中的代码重复

问题描述

我正在为 spring-boot 项目编写 JUnit 测试,但我注意到有很多重复的代码。有什么办法可以避免这种情况。 例如:

示例 1:

@Test
void searchInsideArea() throws Exception {

        when(foundAdvertService.searchInsideArea(searchInsideAreaDto,0)).thenReturn(page);

        String searchinsiderdto=objectMapper.writeValueAsstring(searchInsideAreaDto);

        MvcResult mvcResult=mockmvc.perform(
                post("/found-advert/search-by-area/{pageNumber}",0)
                        .content(searchinsiderdto)
                .contentType(MediaType.APPLICATION_JSON)
                        .header(HttpHeaders.AUTHORIZATION,""))
                .andExpect(status().isOk()).andReturn();
}

示例 2:

@Test
void searchInsideArea() throws Exception{

        when(**lostAdvertService**.searchInsideArea(searchInsideAreaDto,0)).thenReturn(page);

        String searchinsiderdto=objectMapper.writeValueAsstring(searchInsideAreaDto);

        MvcResult mvcResult=mockmvc.perform(
                post("/lost-advert/search-by-area/{pageNumber}",0)
                        .content(searchinsiderdto)
                        .contentType(MediaType.APPLICATION_JSON)
                        .header(org.springframework.http.HttpHeaders.AUTHORIZATION,""))
                .andExpect(status().isOk()).andReturn();
}

如您所见,正在测试两个不同的类,但使用相同的代码。如何避免重复?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)