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

How to check if-statement in method using Mockito and JUnit?(如何使用 Mockito 和 JUnit 检查方法中的 if 语句?)
本文介绍了如何使用 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 语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Sending a keyboard event from java to any application (on-screen-keyboard)(将键盘事件从 java 发送到任何应用程序(屏幕键盘))
How to make JComboBox selected item not changed when scrolling through its popuplist using keyboard(使用键盘滚动其弹出列表时如何使 JComboBox 所选项目不更改)
Capturing keystrokes without focus(在没有焦点的情况下捕获击键)
How can I position a layout right above the android on-screen keyboard?(如何将布局放置在 android 屏幕键盘的正上方?)
How to check for key being held down on startup in Java(如何检查在Java中启动时按住的键)
Android - Get keyboard key press(Android - 获取键盘按键)