gpt4 book ai didi

java - JUnit Spring MVC

转载 作者:行者123 更新时间:2023-12-01 19:02:49 25 4
gpt4 key购买 nike

我想寻求有关如何对以下代码执行单元测试的帮助。我使用Java Spring MVC框架开发它。

@GetMapping("/top3Downtime/{type}/{date}")
public List<Top3DowntimeChart> getTop3DowntimeByDate(@PathVariable String type, @PathVariable
String date)
throws ParseException{

if (type.equals(weekType)) {
String weekStart = date.substring(0, 10);
return top3DowntimeRepository.getTop3DowntimeChartByWeek(dateUtil.getParsedDate(weekStart));

} else if (type.equals(monthType)) {
String monthValue = date.substring(5, 7);
String monthYear = date.substring(0, 4);
String fullStartDate = monthYear + "-" + monthValue + "-" + "01";

return top3DowntimeRepository.getTop3DowntimeChartByMonth(dateUtil.getParsedDate(fullStartDate));

} else if (type.equals(quarterType)) {
String quarterValue = date.substring(0, 2);
String quarterYear = date.substring(3, 7);

return top3DowntimeRepository.getTop3DowntimeChartByQuarter(dateUtil.getFirstQuarterMonth(quarterValue, quarterYear));

} else if (type.equals(yearType)) {
String year = date.substring(0, 4);
beginningFormat = year + startDateOfYear;
endingFormat = year + endDateOfYear;
return top3DowntimeRepository.getTop3DowntimeChartByYear(dateUtil.getParsedDate(beginningFormat));

} else {
return top3DowntimeRepository.getTop3DowntimeChartByDate(dateUtil.getParsedDate(date));
}
}

到目前为止,这是我为 JUnit 测试我的程序编写的代码,但我无法完全覆盖它。错误告诉我缺少一些分支。任何援助将不胜感激。谢谢。

@MockBean
private Top3DowntimeChart top3DowntimeChart;
@MockBean
private VarianceChart varianceChart;
@MockBean
private VarianceChartOnOffSite varianceChartOnOffSite;
@Autowired
private WebApplicationContext webApplicationContext;
@Mock
private DateUtil dateUtil;
@Autowired
private Top3DowntimeRepository top3DowntimeRepository;
private MockMvc mockMvc;

List<Top3DowntimeChart> top3Downtime;

@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();

availabilityImpactChart = new AvailabilityImpactChart(91.90, "NCR", 20);
availPerAtmRatingChart = new AvailPerAtmRatingChart("98", "97");
consecutiveOfflineChart = new ConsecutiveOfflineChart("2020-01-01", 88);
downtimeBreakdownChart = new DowntimeBreakdownChart("97", "85");
downtimeChart = new DowntimeChart(95.95, "Category1", "2020-01-01");
downtimeDistDailyChart = new DowntimeDistDailyChart("nameOfRegion", "atmOutOfService", "beginningOfDay", "cardReader", "cashDistributor", "cashHandler", "commandRejected", "communication", "connection",
"encryptor", "endOfDay", "purgedBin");
downtimeDistOverallChart = new DowntimeDistOverallChart("date", "atmOutOfService", "beginningOfDay", "cardReader", "cashDistributor", "cashHandler", "commandRejected", "communication",
"connection", "encryptor", "endOfDay", "purgedBin");
downtimeIntervTrendChart = new DowntimeIntervTrendChart("eventCategory", "2020-01-01", "00:00:00", 12.00f);
eventCategory = new EventCategory("eventDescription", "eventCategoryString");
heatMapChart = new HeatMapChart(97.12, "phRegion", 20, "2020-01-01");
impactPerRegionChart = new ImpactPerRegionChart("locationName", 25);
intervalChart = new IntervalChart("duration", "time", 15.15f);
overallChart = new OverallChart("2020-01-01", 91.01, 8);
overviewChart = new OverviewChart("region", "availabilityPercentage");
overviewDowntime = new OverviewDowntime("eventDescription", 85.88);
perRegionPerfChart = new PerRegionPerfChart("regionAcronym", 90.00);
top3DowntimeChart = new Top3DowntimeChart("eventCategoryType", "column2", "column3");
varianceChart = new VarianceChart("2020-01-01", 88.90);
varianceChartOnOffSite = new VarianceChartOnOffSite("siteClass", 87.77, 85.00);

}

@Test
public void testGetTop3DowntimeByDate() throws Exception {

when(top3DowntimeChart.getEventCategoryType()).thenReturn("eventCategoryType");
when(top3DowntimeChart.getColumn2()).thenReturn("column2");
when(top3DowntimeChart.getColumn3()).thenReturn("column3");
when(top3DowntimeRepository.getTop3DowntimeChartByDate(dateUtil.getParsedDate("2019-10-10"))).thenReturn(top3Downtime);
//Top3DowntimeChart data = new Top3DowntimeChart("ATM Out of Service", "19.22", "23.15");
//assertNotNull(data);
this.mockMvc.perform(get("/top3Downtime/date/2019-10-10") .accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8));

}
@Test
public void failedGetTop3DowntimeByDate() throws Exception {

when(top3DowntimeChart.getEventCategoryType()).thenReturn("eventCategoryType");
when(top3DowntimeChart.getColumn2()).thenReturn("column2");
when(top3DowntimeChart.getColumn3()).thenReturn("column3");
//Top3DowntimeChart data = new Top3DowntimeChart("ATM Out of Service", "19.22", "23.15");
//assertNotNull(data);
this.mockMvc.perform(get("/top3Downtime/date/") .accept(MediaType.APPLICATION_JSON))
.andExpect(status().isBadRequest());

}

最佳答案

  1. 清理模拟/ Autowiring 的困惑
    • 仅模拟 Controller 中 @autowired 的事物
    • 除非必要,否则删除任何其他模拟
    • 如果您想单独在此 Controller 上实现单元测试,请删除 MockMvc
  2. 模拟该 Controller 调用的所有外部事物
    • top3DowntimeRepository.getTop3DowntimeChartByWeek
    • top3DowntimeRepository.getTop3DowntimeChartByMonth
    • top3DowntimeRepository.getTop3DowntimeChartByQuarter
    • top3DowntimeRepository.getTop3DowntimeChartByYear
  3. 使用 @InjectMocks 将 Mock 注入(inject)此 Controller

见下文:

@InjectMocks 
ControllerNameHere controllerToTest;
  • 在每个测试类中使用不同的参数调用 Controller
  • 使用注入(inject)的模拟调用 Controller 并验证结果

    List<Top3DowntimeChart> result = controllerToTest.getTop3DowntimeByDate("date", "2019-10-10");  
    assertEquals(EXPECTED_SIZE, result.size);

    关于java - JUnit Spring MVC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59607153/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com