Mockito 3.6:在 JUnit4 的@Before 或@BeforeClass 中使用 mockStatic

Mockito 3.6: Using mockStatic in @Before or @BeforeClass with JUnit4

Mockito 3.6 支持在 try-with-resources 块下模拟静态方法,如 here 所述。

有人可以告诉我是否可以在 @Before 中使用 Powermock 模拟静态方法,或者 @BeforeClass 可以 Mockito.mockStatic 用来替换它们而无需完全重写测试 class?

我认为您可能需要进行一些重构。您可以通过在 class 级别创建 MockedStatic 变量来创建静态方法的模拟,并在您的测试中使用它,有时它需要在 @After 块中关闭,例如

MockedStatic<StaticClass> mockedStaticClass;
@Before
public void setUp()
{
  mockedStaticClass = Mockito.mockStatic(StaticClass.class);
}

@After
public void tearDown() throws Exception
{
  mockedStaticClass.close();
}

@Test
public void yourTest()
{
  //make use of mockedStatic variable you created earlier
}