I have a simple DTO class:
@Data // lombok
public class MyObj {
private int id;
private String someProperty;
}
and a class with some computation logic for the DTO object:
public class MyClass {
public String doSomething(MyObj obj) {
// some calculations
}
}
I tried to mock MyClass to use it in some unit tests, but encountered a weird problem. Therefore, I created this minimal test code to illustrate the issue:
@RunWith(MockitoJUnitRunner.class)
public class MyClassTest {
private final MyObj myObjFirst = new MyObj();
private final MyObj myObjSecond = new MyObj();
@Mock
private MyClass myClass;
@Before
public void setUp() {
doReturn("OTHER")
.when(myClass)
.doSomething(any(MyObj.class));
doReturn("FIRST")
.when(myClass)
.doSomething(myObjFirst);
doReturn("SECOND")
.when(myClass)
.doSomething(myObjSecond);
}
@Test
public void doSomething() {
assertEquals("FIRST", myClass.doSomething(myObjFirst)); // fail, actual value "SECOND"
assertEquals("SECOND", myClass.doSomething(myObjSecond));
assertEquals("OTHER", myClass.doSomething(new MyObj()));
assertEquals("OTHER", myClass.doSomething(new MyObj()));
}
}
For some reason, myClass.doSomething(myObjFirst) produces the string "SECOND" instead of the expected "FIRST", therefore the test fails at the first assert.
What am I doing wrong?