Hot questions for Using Mockito in refactoring
Question:
I have a method, I want to test. In there I call a static method of a final Hybris-class (Config.getParameter("aString")
). I want to mock it, but I found out, you can't do that with Mockito. So what would be a good way to approach this? The thing is, I am thinking about refactoring. But I can't change the Config-class, since it is from Hybris.
How can I change my class I want to test, so that I can influence the Config.getParameter("aString")
call?
Thanks!
Answer:
There are two ways to do it:
1.Refactor your code and introduce ConfigWrapper (for example) interface:
public interface ConfigWrapper { public String getParameter(String parameter); public class ConfigWrapperImpl implements ConfigWrapper{ public String getParameter(String parameter){ return Config.getParameter(parameter); } }
Then you should refactor your code and replace Config.* usages by injecting ConfigWrapper. And when you write a test you can easily mock ConfigWrapper with mockito (cause you are using non-static method)
The second way is to use PowerMock instead of mockito:
PowerMock.mockStatic(ClassThatContainsStaticMethod.class)
for more info u can see: https://github.com/jayway/powermock/wiki/MockStatic
Question:
I'm searching for an officially provided method to replace the last line of...
import static org.mockito.BDDMockito.then; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; // ... Runnable mock = mock(Runnable.class); then(mock).should(times(1)).run();
...with something shorter like:
then(mock).should(once()).callMethod();
Why shorter? Because IntelliJ's usually helpful feature shows the parameter's name, resulting in many long code lines:
then(mock).should(times(wantedNumberOfInvocations: 1)).callMethod();
I know that I can easily write such a function, but then I'd either have to duplicate it for a couple of workspace projects or otherwise to introduce a new module, which seems to be overdone to me.
Would be nice if you could point out something like Mockito.atLeastOnce()
for Mockito.atLeast(1)
, just without the atLeast
part :-) Thanks
Answer:
Other alternative is to use simple should()
, which is an alias for single invocation:
then(mock).should().callMethod();