I am new to Mockito 5 and trying to chain the call inside MockedConstruction block. I understand MockedConstruction.constructed() will return a new/different mock object for each instantiation. I am trying to find out if there is any workaround to chain the thenReturn()(or thenThrow()) in the MockedConstruction block other than write multiple test cases.
public class A {
private final String test;
public A(String test) {
this.test = test;
}
public String check() {
return "checked " + this.test;
}
}
public class TestService {
public String purchaseProduct(String param) {
A a = new A(param);
return a.check();
}
}
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.MockedConstruction;
import org.mockito.Mockito;
import static org.mockito.Mockito.*;
public class ConstructorMockTest {
private MockedConstruction<A> mockAController;
@BeforeEach
public void beginTest() {
//create mock controller for all constructors of the given class
mockAController = Mockito.mockConstruction(A.class,
(mock, context) -> {
//implement initializer for mock. Set multiple return value for object A mock methods
when(mock.check()).thenReturn(" Constructor Mock A ").thenReturn(" Constructor Mock A again");
});
}
@Test
public void test() {
TestService service = new TestService();
String serviceResult1 = service.purchaseProduct("test");
//ensure that service returned value from A mock
Assertions.assertEquals(serviceResult1, " Constructor Mock A ");
String serviceResult2 = service.purchaseProduct("test");
//The assertEquals() will show error because the newly instantiated
// mock will always call the first thenReturn() and the remaining
// thenReturn() can never be reached
Assertions.assertEquals(serviceResult2, " Constructor Mock A again");
}
@AfterEach
public void endTest() {
mockAController.close();
}
}