@RunWith(PowerMockRunner.class)是否在每次测试之前为使用@Mock注释的成员注入新的模拟?

时间:2014-03-26 19:26:01

标签: java mockito powermock

......或者在任何测试运行之前它只做了一次吗?

@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?
  }
}

1 个答案:

答案 0 :(得分:3)

与大多数JUnit运行程序一样,

PowerMockRunner创建a brand new test class instance for every test。这有助于确保测试不会相互干扰。

PowerMock源代码有点难以理解,每个JUnit版本的委托和类加载器保留“块”,但是每次调用invokeTestMethod时都可以看到here in PowerMockJUnit44RunnerDelegateImpl:189它得到了来自createTest的新实例,来自createTestInstance

PowerMock然后使用新的模拟填充新实例。 @Mock注入的文档有点难以找到,但我在PowerMock TestListeners wiki page上找到了一些文档。事实证明,AnnotationEnabler类因支持库而异[{3}} - 但都会在beforeTestMethod上重新注入新鲜的模拟。

请注意,测试之间可能会保留静态字段,因此虽然实例字段将为每个测试方法新填充,但静态字段不会。避免在测试中使用可变静态字段,无论您是否使用PowerMock。

相关问题