我有一个 void 方法,即 invokeEllaAsync,我想在 Spring 生态系统中测试它,并在下面提供。该方法还从内部调用另一个 void 方法作为嵌套调用。
下面提供了模拟信息,
@InjectMocks
private EllaService ellaService;
private IrisBo validIrisBo;
@Mock
private EllaRequestDto ellaRequestDtoMock;
@Mock
private EntityServiceConnectable<EllaResponseDto> connectorMock;
@Mock
private EllaResponseDto ellaResponseMock;
@Async
public void invokeEllaAsync( final IrisBo irisBo ) throws EllaGatewayUnsuccessfulResponseException {
try {
callEllaService( irisBo );
}
/**
* Asynchronously call Ella. Determine if traffic is applicable for Ella and if yes forward to Ella.
*
* @param irisEo
* @return List<ResultBo>
* @throws EllaGatewayUnsuccessfulResponseException
*/
catch( EllaGatewayUnsuccessfulResponseException ex ) {
throw new EllaGatewayUnsuccessfulResponseException( ex.getMessage(), ex.getCause() );
}
}
private void callEllaService( final IrisBo irisBo ) throws EllaGatewayUnsuccessfulResponseException {
HttpHeaders elladHeaders = createRequestHeaders( irisBo );
ServiceResponse<EllaResponseDto> response = connector.call( EllaDtoConverter.convertToRequest( irisBo ), elladHeaders );
if( !response.isSuccess() ) {
throw new EllaGatewayUnsuccessfulResponseException( response.getErrorMessage(), response.getException().getCause() );
}
}
我尝试按如下方式测试 invokeEllaAsync
方法,
@Test
public void testInvokeEllaShowsSuccess() {
ServiceResponse<EllaResponseDto> validServiceResponseMock = mock( ServiceResponse.class );
when( connectorMock.call( any(), (HttpHeaders) any() ) ).thenReturn( validServiceResponseMock );
when( validServiceResponseMock.isSuccess() ).thenReturn( true );
ellaService.invokeEllaAsync( validIrisBo );
verify( ellaService, times( 1 ) ).invokeEllaAsync( validIrisBo );
}
我收到下面提供的错误,
org.mockito.exceptions.misusing.NotAMockException:
Argument passed to verify() is of type EllaService 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();
如果我理解正确的话,ellaService
是@InjectMocks
的类型,而不是@Mock
。因此,不执行测试。
如何正确编写测试?
最佳答案
问题是您只能验证模拟组件(用 @Mock 注释)。 EllaService 不是 moc,而是代码中真实类的实例。 @InjectMock注解只是用mocks设置EllaService的私有(private)字段。
通常,在测试 void 方法时,您需要确保使用预期参数调用了一些模拟组件,因此您需要验证的不是 ellaService 调用,而是对 invokeEllaAsync 方法中使用的模拟组件的调用。
关于java - Junit 测试无效响应方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56393561/