0

How can I mock config.getInt("getNoOfDays",100) in MockitoJUnitRunner?

I have tried

     @Test(expected = IllegalStateException.class)
            public void populateAddress() {
                 Mockito.when(Integer.valueOf(Config.getInt("getNoOfDays", 100))).thenReturn(
                Integer.valueOf(100));
    }

1 Answers1

0

Mockito cannot mock statics methods since it is not a good approach to mock them. There is a test library PowerMock that helps to do it.

Here is the example how it can work:

PowerMockito.mockStatic(Integer.class);
BDDMockito.given(Integer.valueOf(...)).willReturn(...);

BTW: In your case you can mock the Config itself.

Uladzislau Kaminski
  • 2,113
  • 2
  • 14
  • 33
  • 1
    Actually, this answer is slightly out of date. Since Mockito 3.4, you can indeed mock static methods, but there has been a long discussion on whether to integrate this feature. In the end, it is mostly useful for legacy applications. (See Mockito [#1013](https://github.com/mockito/mockito/issues/1013)) – Glains Jul 13 '20 at 14:02
  • @Glains Yes, thanks for mentioning new version. I found that release was this month. Here is the documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#48 – Uladzislau Kaminski Jul 13 '20 at 14:12