Does @RunWith(PowerMockRunner.class) inject new mocks for members annotated with @Mock prior to each test?

StackOverflow https://stackoverflow.com/questions/22671145

  •  22-06-2023
  •  | 
  •  

Question

...or does it do it only once, before any test has been run?

@RunWith(PowerMockRunner.class)
public class Tests {
  @Mock
  private ISomething mockedSomething;

  @Test
  public void test1() {
    // Is the value of mockedSomething here
  }

  @Test
  public void test2() {
    // ... guaranteed to be either the same or a different instance here?  Or is it indeterminate?
  }
}
Was it helpful?

Solution

PowerMockRunner, like most JUnit runners, creates a brand new test class instance for every test. This helps ensure that tests don't interfere with one another.

The PowerMock source is a little hard to follow, with per-JUnit-version delegates and classloader-conserving "chunks", but you can see here in PowerMockJUnit44RunnerDelegateImpl:189 that every time invokeTestMethod is called it gets a new instance from createTest, which gets it from createTestInstance.

PowerMock then populates the new instance with fresh mocks. The documentation for @Mock injection is a little tricky to find, but I found some on the PowerMock TestListeners wiki page. As it turns out, the AnnotationEnabler class varies by support library—this is the Mockito one, for instance—but both re-inject fresh mocks on beforeTestMethod.

Note that static fields will likely be conserved between tests, so though instance fields will be populated freshly for every test method, static fields will not. Avoid using mutable static fields in your tests, whether or not you use PowerMock.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top