我正在学习mockito,我从链接中了解了上述功能的基本用法.
但我想知道它是否可以用于任何其他情况?
Koi*_*oer 105
doThrow:在模拟对象中调用方法时想要抛出异常时使用.
public void validateEntity(final Object object){}
Mockito.doThrow(IllegalArgumentException.class)
.when(validationService).validateEntity(Matchers.any(AnyObjectClass.class));
Run Code Online (Sandbox Code Playgroud)
doReturn:在执行方法时要返回返回值时使用.
public Socket getCosmosSocket() throws IOException {}
Mockito.doReturn(cosmosSocket).when(cosmosServiceImpl).getCosmosSocket();
Run Code Online (Sandbox Code Playgroud)
doAnswer:有时您需要对传递给方法的参数执行一些操作,例如,添加一些值,进行一些计算甚至修改它们doAnswer为您提供在调用方法时执行的Answer接口,此接口允许您通过InvocationOnMock参数与参数进行交互.此外,answer方法的返回值将是模拟方法的返回值.
public ReturnValueObject quickChange(Object1 object);
Mockito.doAnswer(new Answer<ReturnValueObject>() {
@Override
public ReturnValueObject answer(final InvocationOnMock invocation) throws Throwable {
final Object1 originalArgument = (invocation.getArguments())[0];
final ReturnValueObject returnedValue = new ReturnValueObject();
returnedValue.setCost(new Cost());
return returnedValue ;
}
}).when(priceChangeRequestService).quickCharge(Matchers.any(Object1.class));
Run Code Online (Sandbox Code Playgroud)
doNothing:是最简单的列表,基本上它告诉Mockito在调用模拟对象中的方法时什么也不做.有时用于void返回方法或没有副作用的方法,或者与您正在进行的单元测试无关.
public void updateRequestActionAndApproval(final List<Object1> cmItems);
Mockito.doNothing().when(pagLogService).updateRequestActionAndApproval(
Matchers.any(Object1.class));
Run Code Online (Sandbox Code Playgroud)
要在接受的答案中添加一些内容......
如果你得到一个UnfinishedStubbingException
,一定要在闭包之后设置要存根的方法,这when
与你编写时不同Mockito.when
Mockito.doNothing().when(mock).method() //method is declared after 'when' closes
Mockito.when(mock.method()).thenReturn(something) //method is declared inside 'when'
Run Code Online (Sandbox Code Playgroud)
小智 7
这取决于您要与之交互的测试替身类型:
换句话说,通过模拟,与合作者唯一有用的交互是您提供的交互。默认情况下,函数将返回 null,void 方法什么也不做。
一个非常简单的例子是,如果您有一个UserService
具有@Autowired
jpa resposirotyUserRepository
...
class UserService{
@Autowired
UserRepository userRepository;
...
}
Run Code Online (Sandbox Code Playgroud)
然后在测试课上UserService
你会做
...
class TestUserService{
@Mock
UserRepository userRepository;
@InjectMocks
UserService userService;
...
}
Run Code Online (Sandbox Code Playgroud)
@InjectMocks
告诉框架采用@Mock UserRepository userRespository;
并将其注入到userService
so 而不是自动装配UserRepository
Mock of的真实实例UserRepository
将被注入到 中userService
。
归档时间: |
|
查看次数: |
167281 次 |
最近记录: |