开发者

What does Mockito.mock do and suggestions why this implementation won´t work when getting rid of Mockito

开发者 https://www.devze.com 2023-03-06 07:25 出处:网络
I have the following interface CatalogVersionService which exposes some services. As well I have a unit test which mocks this interface by using Mockito like this:

I have the following interface CatalogVersionService which exposes some services. As well I have a unit test which mocks this interface by using Mockito like this:

CatalogVersionService catalogVersionService  = Mockito.mock(CatalogVersionService.class);

And injects the catalogVersionService in a resolver implementation named DefaultClassificationClassResolverService like this:

((DefaultClassificationClassResolverService) ccrservice).setCatalogVersionService(catalogVersionService);

// Assert that my resolver will find a single ClassificationClassModel object
ClassificationClassModel single = new ClassificationClassModel();
        assertTrue(ccrservice.resolve(single).contains(single)); //resolver

Up to that point everything works fine until I try to create an integration test and get rid of the Mocked CatalogVersionService interface. As far as I am aware Mockito.mock creates a mock object of given class or interface, in this case CatalogVersionService which is implemented by DefaultCatalogVersionService. So when I try to obtain the real object I do something like this:

catalogVersionService = new DefaultCatalogVersionService();
((DefaultClassificationClassResolverService) ccrservice).setCatalogVersionService(catalogVersionService);

However, after tha开发者_如何学编程t point is where I get a null pointer exception and my resolver test of course fails. So what does Mockito.mock actually do?? Is it a good approach to assume:

CatalogVersionService catalogVersionService  = Mockito.mock(CatalogVersionService.class);
// IS EQUIVALENT TO:
catalogVersionService = new DefaultCatalogVersionService();

Any ideas why the assert is failing?

Thanks in advance


No, it is incorrect to assume that Mockito.mock(...) is the same as instantiating an instance of your DefaultCatalogVersionService. This is not what mocks do.

If you are getting a NullPointerException when using the concrete DefaultCatalogVersionService, this would suggest that something is null within the DefaultCatalogVersionService!

Have you examined the stacktrace to see at what line the NullPointerException occurs, which would help you determine which property/field is null?

It's more than likely that your DefaultCatalogVersionService depends on other classes, which you are not wiring up in your test.

0

精彩评论

暂无评论...
验证码 换一张
取 消