Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spy a service spring having transactional methods

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;
    }

}
like image 749
SEBASTIANNICOLAE BURCHIDRAGOMI Avatar asked Jan 21 '26 12:01

SEBASTIANNICOLAE BURCHIDRAGOMI


1 Answers

According to this issue I found, one possible workaround is to use

So instead of : spy(proxy) use mock(TestSubject.class, delegatesTo(springProxy)).

In your case (untested by me), that would probably be

return Mockito.mock(VirtualControllerService.class, AdditionalAnswers.delegatesTo(virtualControllerService));

See AdditionalAnswers.delegateTo for more information. Note that you can not stub or verify internal method calls in your spied instance (only the method call to the mock object will be tracked). Use case:

Useful for spies or partial mocks of objects that are difficult to mock or spy using the usual spy API. Possible use cases: Already custom proxied object

like image 80
sfiss Avatar answered Jan 24 '26 03:01

sfiss



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!