Mocking a DateFormat class in junit test

henrik

I am trying to Mock a DateFormat class, since it has no purpose in the scope of my unit test. I am using the org.mockito.Mockito library.

Following code:

import static org.mockito.Mockito.when;
import static org.mockito.Mockito.any;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import org.junit.Before;

public class someTest {

    @Mock
    DateFormat formatter; 

    @Before
    public void before() {
        MockitoAnnotations.initMocks(this);
        when(formatter.format(any(Date.class))).thenReturn("2017-02-06");
    }
}

Gives following error:

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: Invalid use of argument matchers! 3 matchers expected, 1 recorded:

-> at someTest.before(someTest.java:33)

This exception may occur if matchers are combined with raw values: //incorrect: someMethod(anyObject(), "raw String"); When using matchers, all arguments have to be provided by matchers. For example: //correct: someMethod(anyObject(), eq("String by matcher"));

For more info see javadoc for Matchers class.

at java.text.DateFormat.format(Unknown Source)
at someTest.before(someTest.java:33)

How do I mock the DateFormat class in a correct way?

Sergii Bishyr

The problem is with implementation of format(Date date)

public final String format(Date date) {
    return format(date, new StringBuffer(),
                  DontCareFieldPosition.INSTANCE).toString();
}

As you can see, it's final. Mockito cannot mock final methods. Instead, it will call the real method. As a workaround, you can mock method format(date, new StringBuffer(), DontCareFieldPosition.INSTANCE)

when(formatter.format(any(Date.class), any(StringBuffer.class), 
                      any(FieldPosition.class)))
    .thenReturn(new StringBuffer("2017-02-06"));

So when method format(date) will call your mocked method the result will be as you expected.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related