static mocking is already registered in the current thread

1.8k Views Asked by At
@RunWith(MockitoJUnitRunner.class)
public class MyTest {
  private AutoCloseable autoCloseable;

  @BeforeEach
  void init() throws InterruptedException {
    autoCloseable = MockitoAnnotations.openMocks(this);
  }

  @AfterEach
  public void tearDown() throws Exception {
    autoCloseeable.close();
  }
  

In one of the tests I'm using Mockito.mockConstruction to mock the behavior of an object created inside the method being tested. When I run the testsuite, the test fails with

org.mockito.exceptions.base.MockitoException: For com.stocktrader.service.ib.ltp.GetStockOrFuturesPrice, static mocking is already registered in the current thread

To create a new mock, the existing static mock registration must be deregistered

If I run the test individually, it succeeds. Any idea why?

1

There are 1 best solutions below

2
On

The error message you are seeing occurs when the static mocking is already registered in the current thread for the class . To create a new mock, the existing static mock registration must be deregistered.

It’s possible that the test runs successfully when run individually because the static mock registration is not present in the current thread. When you run the entire test suite, the static mock registration may be present in another thread, causing the error message you are seeing.

Deregistering the existing static mock registration before creating a new mock should solve this issue.

@RunWith(MockitoJUnitRunner.class)
public class MyTest {
  private AutoCloseable autoCloseable;

  @BeforeEach
  void init() throws InterruptedException {
    autoCloseable = MockitoAnnotations.openMocks(this);
  }

  @AfterEach
  public void tearDown() throws Exception {
    autoCloseeable.close();
  }

  @Test
  public void testMethod() {
    try (MockedStatic<GetStockOrFuturesPrice> mocked = Mockito.mockStatic(GetStockOrFuturesPrice.class)) {
      mocked.when(() -> GetStockOrFuturesPrice.getPrice(Mockito.anyString())).thenReturn(10.0);
      // Your test code here
    }
  }
}