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.
精彩评论