Is there way to mock pojo other then setting values manually in mockito?



consider a method returns class A in my service,

public List<A> method(){
A a=B.method_b();
List<A> list=new ArrayList<>();
for(A aa:a){
A classA=new A();
classA.setVal1(aa.getVal1());
list.add(classA);
}
        return list;
    }

My pojo class

class A{
private int val1;
private int val2;
.
.
.
.
private int val10;
//setter and getter 
}

so in test case ,i wrote as

@Mock
B b;
@Test
public void check(){
 Mockito.when(b.method_b())
        .thenReturn(return_A());
}
private A return_A(){
A a=new A();
a.setVal1(1);
.
.
.
a.setVal10(10);
}

Here everything is working fine .Code coverage is also fine.But my question is ,is there any possible way to avoid above private method that returns class A by using mockito ?

Answer

in a unittest you define the behavior of your class depending on input. This means you have to specify this input. There is no way around it.

There are different ways to do that.

one way it to configure the DTO the way you did.

Another way is to generate the input data. But this has some downsites:
– you still need a method (or class) to do that,
– it makes your test harder to read and understand,
– it introduces failure possibilities in your test making it less reliable,

One more way is to set only those values needed for the current test in the //arrange section of your test method:

@Mock
B b;
@Test
public void check(){
  // arrange
  Mockito.when(b.method_b())
        .thenReturn(return_A());
  A a=new A();
  // values to be used by cut in this test
  a.setVal1(1);
  a.setVal3(3); 

  // act
  // assert 
}


Source: stackoverflow