I have a service class with a method in it. This method calls some other service class's methods:
@Service
public class MyServiceClass {
private final OtherServiceClass otherServiceClass;
//constructor
....
public void myMethod(Object input) {
otherServiceClass.method1(input);
otherServiceClass.method2(input, input.getParameter());
otherServiceClass.method3();
}
}
since these service methods are being tested separately in OtherServiceClass, should I write any tests for myMethod? If yes, how? I'm using Junit5 with Mockito and Spring boot 2.3.3
CodePudding user response:
You can use ArgumentCaptor
(see docs) to verify that you are passing correct arguments to the methods of OtherServiceClass
.
CodePudding user response:
Yes, you still should test these classes. In fact, you still have some logic flow in these methods which serves a purpose.
I.E. you want to make sure that otherServiceClass.method3()
is executed in this service. Without additional test someone can remove this invocation in the future and one will not get a clue that something is wrong.
For that purpose you can use library called BDDMockito
which helps testing behaviours instead of returned values.
You can check out this article to see how you can test the execution of the methods within your service.
Moreover, you should always test the scenarios that involve the input arguments. I.E. ask yourself if the null value is allowed as the input value and then prepare the tests accordingly. At the moment you will end up with the NPE whenever someone passes null as the input.
CodePudding user response:
I think you should test the MyServiceClass.myMethod. As you already said by yourself, the called methods are tested separately so you don't have to test them in detail once again.
The question is what do the called Service methods do and how are you able to test the result. If it is too hard to test it without mocks then you can choose to mock them away and test if they are called, if they are called in the correct order and if they are called with the correct arguments. The risk by doing it this way is, that you later may change the code but with the same functional result but the test fails. Ideally you don't want to test if the code is how the code is now but if the code leads to the correct result.