Thursday, February 18, 2016

How to mock new Date() calls in jUnit test

You can find lots of solutions for this.
I prefer to use Powermock, also because I use it for static code mocking.

The production code:

    @Override
    @Transactional
    public Integer submitTranslationRequest(RequestInfo requestInfo, DocumentTranslationRequestDTO requestDTO) throws PRDException {

         ...
        requestDTO.setSentPoetryDate(new Date());
        ....
    }

Let's see the TEST code:

@RunWith(PowerMockRunner.class)
@PrepareForTest(DocumentTranslationRequestServiceImpl.class)
public class DocumentTranslationRequestServiceImplTest {


    @InjectMocks
    private final DocumentTranslationRequestServiceImpl service = new DocumentTranslationRequestServiceImpl();


    @Test
    public void shouldSubmit() throws Exception {
        // given

        Date eventDate = new Date();
        PowerMockito.whenNew(Date.class).withNoArguments().thenReturn(eventDate);

        // when
        Integer result = service.submitTranslationRequest(requestInfo, dto);

        DocumentTranslationRequestDTO expectedDto = new DocumentTranslationRequestDTO();
        expectedDto.setSentPoetryDate(eventDate);
        // then
        verify(translationRequestDataProvider).saveRequest(eq(expectedDto));

        ...
  }
}

What we need:

        <dependency>
            <groupId>org.powermock</groupId>
            <artifactId>powermock-api-mockito</artifactId>
            <version>1.4.9</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.powermock</groupId>
            <artifactId>powermock-module-junit4</artifactId>
            <version>1.6.4</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.powermock</groupId>
            <artifactId>powermock-core</artifactId>
            <version>1.6.4</version>
            <scope>test</scope>
        </dependency>


If you have problem, error which complains for the javaassist, check the different versions, maybe there is a conflict.



No comments:

Post a Comment