How to test method which invokes another method? In my example I would like to know how to test initComponentsTypeA which invokes create method.
public MyClass{
private List<TypeA> componentsTypeA;
public void initComponents(Config c){
componentsTypeA = initComponentsTypeA(c);
//...
}
private List<TypeA> initComponentsTypeA(Config c){
//...
List<MyObject> someList = c.getSomeList();
List<TypeA> localList = new ArrayList<>();
for(MyObject mo : someList){
localList.add(create(mo));
}
return localList;
}
private TypeA create(MyObject myObject){
// ...
}
}
I know that one solution is to refactor code in this way (show below). But is it necessary? Is it the only solution?
public MyClass{
private List<TypeA> componentsTypeA;
public void initComponents(Config c){
List<MyObject> myObjectList = initComponentsTypeA(c);
componentsTypeA = create(myObjectList)
//...
}
private List<MyObject> initComponentsTypeA(Config c){
//...
List<MyObject> someList = c.getSomeList();
return someList;
}
private List<TypeA> create(List<MyObject> myObjectList){
// ...
}
}
In the second, refactored example the names of the methods are should be also changed, accordingly to their meaning.
You can use mockito and either create a mock that return real methods, then override the behaviour for the method you want to mock, or use spy, which creates a mock that wraps a real instance of your object.
Here's a tutorial on mockito spy.
Edit:
Since the method to be mocked is private, and as @fge mentioned, you would need mocking library that exposes private method. And powermock, does just that.
Given that initComponentsTypeA is a private method, you wouldn't unit test it directly. You only ever want to unit test your public methods which then exercise your private members. You can confirm the effect of your private methods by looking at the side effects created by the calls to your private methods.
So in your case, you would test initComponents. It is likely that in order to see what is going on within initComponents, you would need to pass in a mock Config object so you could verify that it is being used correctly and to control what it returns when getSomeList is called. You would be able to confirm the effect of initComponentsTypeA and create by looking at the effect your call to initComponents had to other properties of the MyClass.
If you don't have a way to see the changes to MyClass, you would need to consider refactoring your class to make that possible. You need to think of your tests as testing MyClass from the persective of another class that is going to use MyClass. If that class can't see or benefit from the effect of calling initComponents then it isn't much use to anyone.
Hopefully that is not too vague of an answer...let me know if you'd like me to clarify anything I've said above.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With