I am trying to write some JUnit tests. In my test class i need to spy a service having transactional methods in the implementation. When i am trying to spy that service, i get this error:
Mockito cannot mock/spy because :
- final class
If i remove @Transactional
from the methods, the spy is working properly. I understand it is a problem because of the service proxy. How can i solve this thing?
My test class:
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = {CreateIfcClusterTaskTest.Config.class})
@DirtiesContext(classMode =
DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
public class CreateIfcClusterTaskTest {
static class Config extends SpringTestConfiguration {
@Bean
@Primary
public VirtualControllerService
virtualControllerService(VirtualControllerService
virtualControllerService) {
return Mockito.spy(virtualControllerService);
}
}
}
My service - VirtualControllerService
:
public interface VirtualControllerService {
JsonHost createVifcHostForWebApi(VirtualController virtualController);
void stopDocker(DockerClient docker, String joinerIpAddress) throws
DockerException, InterruptedException;
}
My service impl - VirtualControllerServiceImpl
:
@Service
public class VirtualControllerServiceImpl implements
VirtualControllerService {
@Override
@Transactional
public JsonHost createVifcHostForWebApi(VirtualController
virtualController) {
JsonHost jsonHost = new JsonHost();
jsonHost.setIP(virtualController.getIpAddress());
jsonHost.setUser(environment.getProperty("VIFC_WEBAPI_USER"));
jsonHost.setPassword(environment.getProperty("VIFC_WEBAPI_PASSWORD"));
return jsonHost;
}
}