mock-maker-inline 使得其他模拟无法工作

问题描述 投票:0回答:1

我尝试了 Mockito 的

mock-maker-inline
“孵化”功能,以便能够模拟最终类(问题描述和讨论here)。从那时起,其他测试都失败了:

org.mockito.exceptions.misusing.NotAMockException: 
Argument passed to when() is not a mock!
Example of correct stubbing:
    doThrow(new RuntimeException()).when(mock).someMethod();

当我定义间谍抛出的异常时。 来自其中一项测试的相关代码:

在@Configuration类中:

@Bean
public MessagePersister messagePersister() {
    return Mockito.spy(new MessagePersister(...));
}

注意:MessagePersister 由 CGLIB 代理。

在测试课中:

@Inject
private MessagePersister messagePersisterSpy;

@Test
public void exceptionInPersisterTest() {
    doThrow(new SomeException("exceptionFromTest")).doCallRealMethod()
            .when(messagePersisterSpy).persistMessages(any());
...
}

这种例外是可以理解的。

messagePersisterSpy
的类别是
MessagePersister$$EnhancerBySpringCGLIB$$6c49f1e2
,但如果我删除
mock-maker-inline
功能,我的间谍属于
MessagePersister$MockitoMock$515952708$$EnhancerBySpringCGLIB$$9523b504
类别,并且测试为绿色。

有什么想法可以解释这种干扰来自哪里吗?我是否可以对此做点什么?

谢谢你!

java spring junit mockito cglib
1个回答
0
投票

经过大量挖掘后找到了解决方案:为未按预期进行模拟的类显式指定模拟制作者

// using annotation
@Mock(mockMaker = MockMakers.SUBCLASS)
Foo mock;
// using MockSettings.withSettings()
Foo mock = Mockito.mock(Foo.class, withSettings().mockMaker(MockMakers.SUBCLASS));
© www.soinside.com 2019 - 2024. All rights reserved.