[英]How to check that a method is not being called using JUnit Mockito Verify
我有一個正在為其編寫 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:
傳遞給 verify() 的參數屬於 $Proxy4 類型,不是模擬!
確保正確放置括號!
請參閱正確驗證的示例:
驗證(模擬)。someMethod();
驗證(模擬,次(10))。someMethod();
驗證(模擬,atLeastOnce())。someMethod();
知道如何在當前上下文中解決此問題。 請舉一個使用當前代碼的例子,以便我得到更好的主意?
您正在混合兩個模擬框架:
JUnitRuleMockery
verify
方法 顯然,它們彼此不兼容。 您的驗證調用看起來還不錯,我相信它會在收到使用Mockito.mock(CntDao.class)
創建的模擬文件后立即運行(使用Mockito.mock(CntDao.class)
)
作為never
替代的選擇,您可以使用Mockito.verifyNoMoreInteractions
或Mockito.verifyZeroInteractions
,但是它們的具體性較低。
除了@Lesiak 的回答之外,這里還有一個基於您的代碼的可重現示例,其中包含測試條件和 BDD 實現(已注釋掉)。
@ExtendWith(MockitoExtension.class)
class CountryProcessTest {
@Mock CountryDAO cntDao;
@Mock
Region region;
@Mock
City city;
@InjectMocks
CountryProcess countryProcess;
@Test
void processCountryLargeSize() {
// given
given(region.getRequiredLongValue()).willReturn(100L);
// when
countryProcess.processCountry(region, city);
// then
verifyNoInteractions(cntDao);
// then(cntDao).shouldHaveNoInteractions(); // BDD implementation
}
@Test
void processCountrySmallSize() {
// given
given(region.getRequiredLongValue()).willReturn(10L);
// when
countryProcess.processCountry(region, city);
// then
verify(cntDao).addCountryLandMark(city);
verifyNoMoreInteractions(cntDao);
// then(cntDao).should().addCountryLandMark(any()); // BDD implementation
// then(cntDao).shouldHaveNoMoreInteractions(); // BDD implementation
}
}
此處提供其余類以供參考。
地區
public class Region {
private int size;
public Long getRequiredLongValue() {
return Integer.toUnsignedLong(size);
}
}
抽象國家進程
public abstract class AbstractCountryProcess {
CountryDAO cntDao;
protected abstract boolean processCountry(Region region, City city);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.