How to check if-statement in method using Mockito and JUnit?

前端 未结 3 671
时光说笑
时光说笑 2021-01-15 09:05

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

public class FilterDataController {

    public static final String DATE_FORMAT = \"y         


        
3条回答
  •  时光说笑
    2021-01-15 09:32

    You will have to mock FilterDataProvider and then inject this into your test class using InjectMocks.

    getPossibleFilterData will be the method under test, so choose any specific date (use Calendar.set(...), then Calendar.getTime()) and send this same date as both the startDate and endDate.

    Now after getPossibleFilterData is completed, you can verify whether filterDataProvider.getPossibleCountries was called with a end Date that is one millisecond more than the start date. This can be done through Calendar.getTimeInMillis() inside the mocked class's method, or by verifying with Mockito with a Date that is one millisecond more than the date that was originally specified.

    Edit: Code example provided:

    public class FilterDataControllerTest {
        @Test
        public void testSameDate() {
            FilterDataProvider provider = Mockito.mock(FilterDataProvider.class);
            FilterDataController controller = new FilterDataController(provider);
    
            Date startDate = new GregorianCalendar(2016, Calendar.JANUARY, 11).getTime();
            Date endDate = new GregorianCalendar(2016, Calendar.JANUARY, 11).getTime();
            Date expectedEndDate = new Date(endDate.getTime() + TimeUnit.DAYS.toMillis(1) - 1);
    
            controller.getPossibleFilterData(startDate, endDate);
    
            Mockito.verify(provider).getPossibleCountries(Mockito.eq(startDate), Mockito.eq(expectedEndDate));
        }
    }
    

提交回复
热议问题