Wednesday, 7 August 2013

Redundant methods across several unit tests/classes

Redundant methods across several unit tests/classes

Say in the main code, you've got something like this:
MyClass.java
public class MyClass {
public List<Obj1> create(List<ObjA> list) {
return (new MyClassCreator()).create(list);
}
// Similar methods for other CRUD operations
}
MyClassCreator.java
public class MyClassCreator {
Obj1Maker obj1Maker = new Obj1Maker();
public List<Obj1> create(List<ObjA> list) {
List<Obj1> converted = new List<Obj1>();
for(ObjA objA : list)
converted.add(obj1Maker.convert(objA));
return converted;
}
}
Obj1Maker.java
public class Obj1Maker {
public Obj1 convert(ObjA objA) {
Obj1 obj1 = new Obj1();
obj1.setProp(formatObjAProperty(objA));
return obj1;
}
private String formatObjAProperty(ObjA objA) {
// get objA prop and do some manipulation on it
}
}
Assume that the unit test for Obj1Maker is already done, and involves a
method makeObjAMock() which mocks complex object A.
My questions:
For unit testing MyClassCreator, how would I test create(List<ObjA> list)?
All the method really does is delegate the conversion from ObjA to Obj1
and runs it in a loop. The conversion itself is already tested. If I were
to create a list of ObjA and tested each object in the list of Obj1 I get
back, I would have to copy makeObjAMock() into MyClassCreator's unit test.
Obviously, this would be duplicate code, so is using verify() enough to
ensure that create(List list) works?
For unit testing MyClass, again, its create(List<ObjA>) method just
delegates the operation to MyClassCreator. Do I actually need to test this
with full test cases, or should I just verify that MyClassCreator's create
method was called?
In the unit test for Obj1Maker, I checked that the properties Obj1 and
ObjA corresponded to each other by doing assertEquals(obj1.getProp(),
formatObjAProperty(objA)). However, that means I had to duplicate the code
for the private formatObjAProperty method from the Obj1Maker class into
its unit test. How can I prevent code repetition in this case? I don't
want to make this method public/protected just so I can use it in a unit
test. Is repetition acceptable in this case?
Thanks, and sorry for the lengthy questions.

No comments:

Post a Comment