Following is my class where I need to mock "resourceManager.getLicenseSources(licenseId)", how this can be achieved?
class LicenseSourceImpl{
-----
ResourceManager resourceManager = ManagerFactory.getInstance(ResourceManager.class);
List<Source> sources = resourceManager.getLicenseSources(licenseId);
-----
}
Few things I've tried:
Mock ManagerFactory itself
ManagerFactory mf = Mockito.mock(ManagerFactory.class); Mockito.when(mf.getInstance(any())).thenReturn(resourceManager); Mockito.when(resourceManager.getLicenseSources(LICENSE_ID)).thenReturn(sources);
This fails with java.lang.NullPointerException: Cannot invoke "java.lang.Class.getName()" because "clazz" is null
Mock ManagerFactory and static mock
ManagerFactory mf = Mockito.mock(ManagerFactory.class); Mockito.when(mf.getInstance(ResourceManager.class)).thenReturn(resourceManager); Mockito.when(resourceManager.getLicenseSources(LICENSE_ID)).thenReturn(sources);
This fails with
org.mockito.exceptions.misusing.MissingMethodInvocationException:
when() requires an argument which has to be 'a method call on a mock'.
For example:
when(mock.getArticles()).thenReturn(articles);
- Spy on factory static method ResourceManager resourceManager = spy(ManagerFactory.getInstance(ResourceManager.class)); but this not mocking the factory instance and creates a new instance always
Is there a way to mock for these situations?
You would have to use
Mockito.mockStatic
to mock a static method. See Mockito javadoc on how to do it. But better design would be to avoid accessing the static factory in your class but rather have theResourceManager
injected, so that you can inject a regular mock in your test...