7

Mockito 3.6 supports mocking static methods under a try-with-resources block as explained here.

Can someone let me know if static methods are mocked using Powermock in @Before or @BeforeClass can Mockito.mockStatic be used to replace them without an entire rewrite of the test class?

tuk
  • 5,941
  • 14
  • 79
  • 162
  • Like @John said, this method works fine. My experience has been that the mock ***has*** to be closed in the After/AfterEach block, though. Otherwise you get a 'mock in use' error when the next test method is invoked. – JohnG42 Feb 11 '21 at 20:05

1 Answers1

14

I think you might need to do a little bit of refactoring. You can create mocks of static methods by creating a MockedStatic variable at class level and use that in your tests and also sometimes it needs to be closed in the @After block, something like

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
}
John
  • 272
  • 1
  • 3
  • 12
  • Nice one thanks. May be in variable declaration we could skip the type if we have multiple test cases with different static classes like MockedStatic mockedStaticClass; – Musa May 31 '22 at 15:40