junit 静态模拟已在当前线程中注册,若要创建新的模拟,

mm5n2pyu  于 11个月前  发布在  其他
关注(0)|答案(1)|浏览(395)

在我对正在测试的类(ConsumerKafkaCardReplacementService)做了一些更改之后,我得到了很多这样的错误:

ConsumerKafkaCardReplacementServiceTest > processCardReplacementSuccessfulWithCIDCredit FAILED
    org.mockito.exceptions.base.MockitoException: 
    For com.api.loyalty.event.listener.global.RewardsProductConfigService, static mocking is already registered in the current thread

    To create a new mock, the existing static mock registration must be deregistered
        at com.api.loyalty.event.listener.service.ConsumerKafkaCardReplacementServiceTest.processCardReplacementSuccessfulWithCIDCredit(ConsumerKafkaCardReplacementServiceTest.java:308)

字符串
对于静态mocking,每个mock都在测试方法结束时关闭:

service = Mockito.mockStatic(RewardsProductConfigService.class);  <-- (line 308)
    service.when(()->RewardsProductConfigService.queryRewardsProductConfigMap(Mockito.any(), Mockito.any())).thenReturn(Optional.of(TestUtil.getCSSSCProductDetails()));   
    ...

    service.close();


未对RewardsProductConfigService类、queryRewardsProductConfigMap方法、TestUtil类、getCSSSCProductDetails方法进行更改。也未对测试类和测试方法进行更改。
我尝试用以下代码注解测试类:

@FixMethodOrder(MethodSorters.NAME_ASCENDING)


以及:

@TestMethodOrder(MethodOrderer.MethodName.class)


这个问题仍然存在,知道为什么吗?

sqyvllje

sqyvllje1#

有两种方法可以解决它:
尝试在Try中声明MockedStatic,如下所示:

try (MockedStatic<DateUtil> mockedStaticDateUtil = mockStatic(DateUtil.class)) {
mockedStaticDateUtil.when(() -> DateUtil.llamadaVigente(Mockito.any(), Mockito.anyInt())).thenReturn(true);
ResponseEntity responseEntity = ringController.getLlamada(ID_LLAMADA_CIFRADO);
your code.....
 } catch (Exception e) {
            throw new RuntimeException(e);
}

字符串
或尝试以下操作:

public Class Test {
        private static CloseableHttpClient httpClientMock;
        private static MockedStatic<HttpClients> httpClientsMockedStatic;
        @BeforeClass
        public static void setUp() throws IOException {
            httpClientMock = mock(CloseableHttpClient.class);
    httpClientsMockedStatic = Mockito.mockStatic(HttpClients.class, Mockito.RETURNS_DEEP_STUBS);
    httpClientsMockedStatic.when( () -> HttpClients.custom().setRetryHandler.build()).thenReturn(httpClientMock);
    // You can also configure the behavior of above line in whatever test method you would like
}


参考https://www.reddit.com/r/javahelp/comments/xpsk5x/how_can_i_resolve_a_static_mocking_is_already/

相关问题