I am curious about the best / recommended approach to follow when writing a unit test.
If I can easily create the specific values that would get passed for a function, should I create those in my unit tests and use them? Or can I use any()
to mock for all values?
class Foo {
bool func1(String abc, int xyz, Bar bar) {
// ...
}
}
If I have a class like this that I want to mock for a specific behavior, which is a better approach?
@Mock
Foo mockFoo;
-
Bar dummyBar = getTestBar(); when(mockFoo.func1("value1", 1, dummyBar)).thenReturn(true);
-
when(mockFoo.func1(anyString(), anyInt(), any())).thenReturn(true);
I am trying to identify when to use each. I feel using specific values will be better whenever possible and if it is simple to create those values. Use any()
only when it is not easy to create such objects. i.e. Say I am refactoring a codebase and I see almost all unit tests are using any()
even if I could use specific values. Will it be worth doing some cleanup on the code and make the unit tests use specific values?