Skip to content

Junit test for model class

This question is about best practice rather than any issues or problem. I have a service method below that I am trying to test. myDAO is DAO class that will be injected and has all database call code.

public List<MyObject> getMyObject(String inputParameter){
    List<MyObject> objectList = myDAO.getObjectList(inputParameter);
    return objectList 

And my Junit test case using mockito is

public class MyClassTest{
    MyClass myClass;

    MyDAO myDAO;

    private MyObject myObj;
    private List<MyObject> objList;

    public void setUp() throws Exception {  
        myObj = new MyObject();
        //I am calling all setter method to prepare myObj here
        objList = new ArrayList<MyObject>();


    public void testGetMyObject(){

        List<MyObject> result =  myClass.getMybject(null);
        assertThat(" Quantity should return 10", result.getQuantity(), is(10));
        // and all asserts....

Everything is fine and working. My main problem here is MyObject is a modal class with 200 parameter.

Now for code coverage I have to call 200 setter methods while preparing objects and asserts 200 getter methods for junit test. I think this is not a good idea. what is better practice and how to cover this kind of modal class on unit test code coverage.



There has always been huge debate on best practice for writing unit test cases. So for this kind of question, there will not be definitive answer. For me writing test cases for getter and setter just to make code coverage percentage high is stupid. But Sometime your choice and your preference doesn’t count.

Despite your code need refactoring, you can use some API that makes your job easier. SmartUnit is one of those, that you can use to test your POJO. These API allows you to write only few lines and behind the scene, cover all your getter/setter code coverage.