gpt4 book ai didi

java - 如何使用 JUnit Mockito 验证检查方法是否未被调用

转载 作者:行者123 更新时间:2023-12-02 01:31:48 25 4
gpt4 key购买 nike

我正在为一个类编写 JUnit 测试。我正在尝试测试是否从未调用过特定方法。

public class CountryProcess extends AbstractCountryProcess {

private static final Logger log = LoggerFactory.getLogger(CountryProcessor.class);
private static final Long MAX_FILE = 20l;

@Override
protected boolean processCountry(Region region, City city) {
Long maxFile = region.getRequiredLongValue(SIZE);

if (maxFile < MAX_FILE) {
cntDao.addCountryLandMark(city);
}
else {
log.warn("File size was big");
}

return true;
}

测试类是:

public class CountryProcessTest {

@Rule
public final JUnitRuleMockery context = new JUnitRuleMockery();
private final CntDao cntDao = context.mock(CntDao.class);

@Before
public void setup() {
Injector injector = Guice.createInjector(new AbstractModule() {
@Override
protected void configure() {
bind(cntDao.class).toInstance(cntDao);
}
});
}

@Test
public void shouldIgnoreIfFileSizeBiggerThanPermitted() {
//some code to make it trigger ELSE statement above...
verify(cntDao, never()).addCountryLandMark(anyString());
}
}

但这会返回以下错误:

org.mockito.exceptions.misusing.NotAMockException:

Argument passed to verify() is of type $Proxy4 and is not a mock!

Make sure you place the parenthesis correctly!

See the examples of correct verifications:

verify(mock).someMethod();

verify(mock, times(10)).someMethod();

verify(mock, atLeastOnce()).someMethod();

知道如何在当前情况下解决这个问题。请使用当前代码给出一个示例,以便我得到更好的想法?

最佳答案

您正在混合两个模拟框架:

  • jMock - JUnitRuleMockery
  • Mockito - 验证方法

显然,它们彼此不兼容。您的验证调用看起来没问题,我相信一旦收到使用 Mockito 创建的模拟(使用 Mockito.mock(CntDao.class)),它就会立即工作

作为never的替代方案,您可以使用Mockito.verifyNoMoreInteractionsMockito.verifyZeroInteractions,但它们不太具体。

关于java - 如何使用 JUnit Mockito 验证检查方法是否未被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55924832/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com