如何使用 Mockito 和 JUnit 检查方法中的 if 语句?

时间:2023-05-02
本文介绍了如何使用 Mockito 和 JUnit 检查方法中的 if 语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我有我应该测试的方法.代码(当然有些部分被剪掉了):

I have method that I should test. Code (of course some parts were cut):

public class FilterDataController {

    public static final String DATE_FORMAT = "yyyy-MM-dd";

    @Autowired
    private FilterDataProvider filterDataProvider;

    @ApiOperation(value = "Get possible filter data",response = ResponseEntity.class)
    @ApiResponses(value = {
            @ApiResponse(...),
            @ApiResponse(...)})
    @RequestMapping(path = "...", method = RequestMethod.GET)
    public ResponseEntity<Object> getPossibleFilterData(
            @RequestParam(value = "startDate") @DateTimeFormat(pattern=DATE_FORMAT) final Date startDate,
            @RequestParam(value = "endDate") @DateTimeFormat(pattern=DATE_FORMAT) final Date endDate) {
        if (endDate.compareTo(startDate) == -1){
            throw new ValueNotAllowedException("End date should be after or equal start date");
        }
        else {
            Date newEndDate = endDate;
            if (startDate.equals(endDate)){
                newEndDate = new Date(endDate.getTime() + TimeUnit.DAYS.toMillis(1) - 1);
            }

            List<String> possibleCountries = Lists.newArrayList(filterDataProvider.getPossibleCountries(startDate, newEndDate));

            return new ResponseEntity<>(new FilterResponse(possibleCountries),HttpStatus.OK);
        }
    }   
}

问题:如何使用 Mockito 和 JUnit 检查方法 getPossibleFilterData 中的 if 语句?我想将相等的日期传递给方法,然后检查我的 if 语句是否正常工作.

Question: how to check if-statement in method getPossibleFilterData using Mockito and JUnit? I want pass equal dates to method then check that my if-statement works properly.

推荐答案

如果你真的想要一个 单元测试而不是集成测试,你可以依赖注解 @Mock 来模拟你的服务 FilterDataProvider@InjectMocks 来将你的模拟注入到你的 FilterDataController 实例中.

If you really want a pure unit test not an integration test, you could rely on the annotation @Mock to mock your service FilterDataProvider and @InjectMocks to inject your mock into your instance of FilterDataController.

那么你可以提出 3 个测试:

  1. 一个日期正确但不同的测试,
  2. 另一个日期正确但相等的日期
  3. 最后一个日期不正确会抛出 ValueNotAllowedException,可以使用 @Test(expected = ValueNotAllowedException.class) 进行测试.
  1. One test where the dates are corrects but different,
  2. Another one where the dates are corrects but equal
  3. And the last one where the dates are incorrect which will thrown a ValueNotAllowedException that could be tested out of the box using @Test(expected = ValueNotAllowedException.class).

如果您需要确保 filterDataProvider.getPossibleCountries(startDate, newEndDate) 已使用您需要使用的预期参数调用 verify.

If you need to make sure that filterDataProvider.getPossibleCountries(startDate, newEndDate) has been called with the expected arguments you need to use verify.

代码会是这样的:

@RunWith(MockitoJUnitRunner.class)
public class FilterDataControllerTest {
    @Mock
    FilterDataProvider filterDataProvider;
    @InjectMocks
    FilterDataController controller;

    @Test(expected = ValueNotAllowedException.class)
    public void testGetPossibleFilterDataIncorrectDates() {
        controller.getPossibleFilterData(new Date(1L), new Date(0L));
    }

    @Test
    public void testGetPossibleFilterDataCorrectDates() {
        // Make the mock returns a list of fake possibilities
        Mockito.when(
            filterDataProvider.getPossibleCountries(
                Mockito.anyObject(), Mockito.anyObject()
            )
        ).thenReturn(Arrays.asList("foo", "bar"));
        ResponseEntity<Object> response = controller.getPossibleFilterData(
            new Date(0L), new Date(1L)
        );
        Assert.assertEquals(HttpStatus.OK, response.getStatusCode());
        // Make sure that 
        // filterDataProvider.getPossibleCountries(new Date(0L), new Date(1L))
        // has been called as expected
        Mockito.verify(filterDataProvider).getPossibleCountries(
            new Date(0L), new Date(1L)
        );
        // Test response.getBody() here
    }

    @Test
    public void testGetPossibleFilterDataEqualDates() {
        // Make the mock returns a list of fake possibilities
        Mockito.when(
            filterDataProvider.getPossibleCountries(
                Mockito.anyObject(), Mockito.anyObject()
            )
        ).thenReturn(Arrays.asList("foo", "bar"));
        // Call the controller with the same dates
        ResponseEntity<Object> response = controller.getPossibleFilterData(
            new Date(1L), new Date(1L)
        );
        Assert.assertEquals(HttpStatus.OK, response.getStatusCode());
        Mockito.verify(filterDataProvider).getPossibleCountries(
            new Date(1L), new Date(TimeUnit.DAYS.toMillis(1))
        );
        // Test response.getBody() here
    }
}

这篇关于如何使用 Mockito 和 JUnit 检查方法中的 if 语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:使用 Mockito 匹配特定类型的空列表 下一篇:如何让 Powermock 与 Dexmaker 一起工作

相关文章