问题描述
我想使用严格的模拟,至少在第一次开发一些针对旧代码的测试时,所以如果我没有专门定义期望,那么在我的模拟上调用的任何方法都会抛出异常。
I'd like to use strict mocks, at least when developing for the first time some tests against old code, so any methods invoked on my mock will throw an exception if I didn't specifically define expectations.
从我看到的情况来看,如果我没有定义任何期望,Mockito将只返回null,稍后会在其他地方导致NullPointerException。
From what I've come to see, Mockito if I didn't define any expectations will just return null, which will later on cause a NullPointerException in some other place.
是否可以这样做?如果是,怎么做?
Is it possible to do that? If yes, how?
推荐答案
你想要它做什么?
您可以将其设置为 ,它避免了NPE并包含一些有用的信息。
You can set it to RETURN_SMART_NULLS, which avoids the NPE and includes some useful info.
你可以用自定义实现替换它,例如,从它的引发异常回答
方法:
You could replace this with a custom implementation, for example, that throws an exception from its answer
method:
@Test
public void test() {
Object mock = Mockito.mock(Object.class, new NullPointerExceptionAnswer());
String s = mock.toString(); // Breaks here, as intended.
assertEquals("", s);
}
class NullPointerExceptionAnswer<T> implements Answer<T> {
@Override
public T answer(InvocationOnMock invocation) throws Throwable {
throw new NullPointerException();
}
}
这篇关于是否有可能与Mockito做严格的嘲笑?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!