1. Mock private member of a class
Example to mock a private member "treeTypeProvider" of class CustomProvider.java
Field field = CustomProvider.class.getDeclaredField("treeTypeProvider");
field.setAccessible(true);
field.set(provider, treeTypeProvider);
2. Mocking a Static class
Make sure you mock a Static class with a try-with-resources. Not doing so will affect Junit execution of other related classes using this Static class somewhere else in other Junit class.
try (MockedStatic<SampleUtils> utils = Mockito.mockStatic(SampleUtils.class)) {
utils.when(() -> SampleUtils.testMethod(node)).thenReturn(mockedNode);
......
......
}
3. Mocking object construction
Example to mock a construction statement like:
DocsProcessor processor = new DocsProcessor();
Mock it like below:
try (MockedConstruction< DocsProcessor > processor = Mockito.mockConstruction(DocsProcessor.class)) {
// Call any method that calls the DocsProcessor class constructor
......
......
// Verify that constructor was called once
assertEquals(1, accessibilityProcess.constructed().size());
}
No comments:
Post a Comment