I read this answer about unit-test a wrapper method. In following code:
public static Object methodA(Object arg) {
if (arg == null) {
return null;
} else {
return methodB();
}
}
It looks reasonable that I don't need to test all functionality in methodB()
, just test 2 cases where arg
is null and not because methodB()
should be tested already.
However, if methodB()
is private method, I should test all functionality that methodB()
will provide because according to another answer, private methods are implementation details.
The problem is, if I have 2 methods methodA1()
and methodA2()
and they all call methodB()
like this:
public static MyObject methodA1(int x) {
MyObject obj = new MyObject();
obj.setX(x);
return methodB(obj);
}
public static MyObject methodA2(int y) {
MyObject obj = new MyObject();
obj.setY(y);
return methodB(obj);
}
private static MyObject methodB(MyObject obj) {
// doSomething with obj
return obj;
}
Should I test methodA1()
and methodA2()
separately? Or I can just test the private method methodB()
because methodA1()
and methodA2()
are just wrapper methods of methodB()
, so if methodB()
is correctly tested, I won't need to test methodA1()
and methodA2()
at all.
EDIT:
I wrote separate tests for public methods at first. But the problem is, if there are many variations of the methodA
, and some of the functionalities / requirements are shared in some of them, then the code of the test cases will be duplicated. That's why I wonder if I should test private method methodB()
.
The real problem I met is I have requirement to add a record in database, and there are many different APIs I should provide. For example, I should provide:
MyObject addMale(String name, String job); // fill sex with "Male"
MyObject addStudent(String name, String sex); // fill job with "Student"
And all of them checks the parameter is valid or not, fill the field that is not specified and call the private method to actually insert the record into the database, which is so called methodB()
.
There are many APIs like this, so if I can only test methodB()
with all fields situation, maybe I can reduce the duplication of the test cases, but is that a good practice to do the unit tests like this?
EDIT2:
I know I can test private methods because I used reflection in my other test cases, and I know it can invoke private methods, too. But my question is about in this situation, testing private methods is a proper solution or not.