I have a Spring Boot project and trying to use PowerMockito to mock an object that is created inside the method.
I have some code that is declaring a new Object that is extending an Abstract class:
@Service
public class InstanceService {
public Instance createJenkinsInstance(RequestSpecification request){
ParentInstance instance = new DefaultInstance(kubernetesUtil);
instance.provisionForNewInstance(request);
...
}
}
The DefaultInstance class:
public class DefaultInstance extends ParentInstance {
public DefaultInstance(KubernetesUtil kubernetesUtil) {
super(kubernetesUtil);
}
public DefaultInstance(KubernetesUtil kubernetesUtil, Environment env) {
super(kubernetesUtil, env);
}
The ParentInstance class:
@Data
public abstract class ParentInstance {
public ParentInstance(KubernetesUtil kubernetesUtil) {
this.kubernetesUtil = kubernetesUtil;
/*some code*/
}
public ParentInstance(KubernetesUtil kubernetesUtil, Environment env) {
this.kubernetesUtil = kubernetesUtil;
this.env = env;
/*some code*/
}
/* Class contains more functions */
My test looks like the following:
@RunWith(PowerMockRunner.class)
@PrepareForTest({InstanceService.class})
public class InstanceServicePowerMockTest {
@Test
public void testCreateInstance() throws Exception {
logger.info("in testCreateInstance2 mock");
DefaultInstance instanceMock = PowerMockito.mock(DefaultInstance.class);
PowerMockito.whenNew(DefaultInstance.class)
.withArguments(any())
.thenReturn(instanceMock);
PowerMockito.when(instanceMock.provisionForNewInstance(any())).thenReturn(true);
RequestSpecification requestSpecification = new RequestSpecification();
requestSpecification.setName("test");
InstanceService instanceService = new InstanceService();
instanceService.createJenkinsInstance(requestSpecification);
verifyNew(DefaultInstance.class).withArguments(any());
}
}
My test isn't working, I notice that the DefaultInstance is being created in the test rather than using the mocked object I have created. I have searched around online for a while, and tried different things I found others doing. I'm wondering if the issue is I'm trying to mock an object that extends an Abstract class. How can I fix this?
Btw, the InstanceService class autowires some DAO classes to save objects to the Database. Does powermock support this?