I face some situations similar to the following simplified one:
@Component class ServiceOne {
@Autowired ServiceTwo two;
void act() {
...
two.a();
...
}
}
@Component class ServiceTwo {
// suppose it has a LOT of methods
void a() { ... }
void b() { ... }
void c() { ... }
...
void z() { ... }
}
In other words, ServiceOne
depends on only one (or a few) methods of ServiceTwo
, but ServiceTwo
itself has exposed a lot of methods.
Now I need to test ServiceOne
.
// (delete this sentence) Shall I mock ServiceTwo
? In other words, is the following the best practice, or bad code smell?
Question: Is there a more efficient way which requires less boilerplate code? Does this lead to maintenance issues? Is there an approach which does not force me to mock 9 unrelated methods?
@Test class ServiceOneTest {
@Component ServiceOne one;
@MockBean ServiceTwo two; // or use Mockito.mock or sth like that, unrelated to question
void testAct() {
when(two.a()).thenReturn(...);
one.act();
}
}
I demonstrate the problem using Java Spring, but surely it is more general and is not limited to that. (For example, this is also a problem when I test Flutter code.)