java - Mock方法实现Junit mockito

标签 java junit mocking mockito

我正在尝试测试以下类(class):

public class PreprocessorServiceImpl implements PreprocessorService
{
private static final Logger LOG = LoggerFactory.getLogger( PreprocessorServiceImpl.class );


private FileServiceProvider fileServiceProvider;

private PreProcessorApiService preprocessorApiService;

private ScanProcessingHelper scanProcessingHelper;

private DocumentProcessingService docProcessingService;

private CacheTimeOutHandler cacheTimeHandler;
private DocumentEventLogger docEventLogger;
private ScanProcessingService scanProcessingService;
private EventLogger eventLogger;
private ScanTrackLogger scanTrackLogger;

//Getters and setters.

@Override
public void processDocument( KafkaDocumentMetaData kafkaDocumentMeta )
{
    APIKeyConfigurationVO apiConfigurationsVo = kafkaDocumentMeta.getCustomerConfiguration();
    DocumentRequest documentRequest = kafkaDocumentMeta.getDocumentRequest();

    LOG.info( "Started preprocessing for documentId: {}", documentRequest.getDocumentId() );
    PreprocessorApiResponse apiResponse;

    try {
        byte[] documentInBytes = getDocumentFileInBytes( documentRequest, apiConfigurationsVo ); //Download from cloud
        docEventLogger.logDocIdEvent( documentRequest.getDocumentId(), EventEnum.FILE_DOWNLOADED );
        apiResponse = preprocessorApiService.preProcess(
            documentRequest.getDocumentRequestAdditionalInfo().getPreProcessingModelUrl(), documentInBytes,
            documentRequest.getDocumentId() );
        documentRequest.setPreprocessorApiResponse( apiResponse );
    } catch ( Exception e ) {
        //If download / ML api failed unexpectedly, then mark it for failure
        handleFailure( documentRequest, apiConfigurationsVo, e );
        return;
    }

    //code to process further in case of success
}

private void handleFailure( DocumentRequest documentRequest, APIKeyConfigurationVO apiConfigurationsVo, Throwable thr )
{
    LOG.error( "Exception occured while processing document. marking it as failed.", thr );
    docProcessingService.persistAndModify( documentRequest, DocumentStatus.FAILED, cacheTimeHandler.getDocumentTimeOut() );//to redis
    docProcessingService.publishDocumentReqMeta( documentRequest, apiConfigurationsVo );//to result analyzer
    docEventLogger.logDocIdFailureEvent( documentRequest.getDocumentId(), thr );
}

}

有一个方法可以更新 docProcessingService.persistAndModify() 中对象的状态

documentRequest.setStatus(documentStatus.getStatus());

如下:

public void persistAndModify( DocumentRequest documentRequest, DocumentStatus documentStatus, int timeToLive )
{
    LOG.debug( "Persisting document request with document id {} and status {}", documentRequest.getDocumentId(),
        documentRequest.getStatus() );
    documentRequest.setStatus( documentStatus.getStatus() );
    persistResponse( documentRequest.getDocumentId(), documentRequest, timeToLive );
    LOG.info( "Updated document request and  status to: {} for documentId: {}", documentRequest.getStatus(),
        documentRequest.getDocumentId() );
}

我不想执行完整的方法。但只要设置documentRequest的状态即可至documentStatus 。使用 junit mockito 可以实现这一点吗?

我尝试使用doAnswer但它抛出NPE。 FOllwing 是我的代码。

Mockito.doAnswer( invocation -> {

        Object[] args = invocation.getArguments();
        DocumentRequest modified = ( (DocumentRequest) args[0] );
        modified.setStatus( DocumentStatus.FAILED.getStatus() );
        return null;

    } ).when( docProcessingService ).persistAndModify( any(), any(), any() );
    //.
    //.data population code
    //.
    assertEquals( docRequest.getStatus(), DocumentStatus.INITIATED.getStatus() );
    preprocessorService.processDocument( kafkaMessage );
    assertEquals( docRequest.getStatus(), DocumentStatus.FAILED.getStatus() );

它会抛出 NPE

} ).when( docProcessingService ).persistAndModify( any(), any(), any() );

我已经添加了-

@RunWith ( MockitoJUnitRunner.class)

MockitoAnnotations.initMocks( PreprocessorServiceTests.class );

并使用@Mock进行 mock

 @Mock
private DocumentProcessingService docProcessingService;

doAnswer适合我的用例还是还有其他什么?如何在模拟方法时给出方法实现?

如果这是一个愚蠢的问题,请原谅。我刚开始使用mockito。

编辑:添加堆栈跟踪

java.lang.NullPointerException
at my.package.service.PreprocessorServiceTests.testDocumentDownloadFailure(PreprocessorServiceTests.java:114)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.mockito.internal.runners.DefaultInternalRunner$1$1.evaluate(DefaultInternalRunner.java:44)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.mockito.internal.runners.DefaultInternalRunner$1.run(DefaultInternalRunner.java:74)
at org.mockito.internal.runners.DefaultInternalRunner.run(DefaultInternalRunner.java:80)
at org.mockito.internal.runners.StrictRunner.run(StrictRunner.java:39)
at org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:163)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
at org.junit.vintage.engine.execution.RunnerExecutor.execute(RunnerExecutor.java:40)
at java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:184)
at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
at java.util.Iterator.forEachRemaining(Iterator.java:116)
at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:151)
at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:174)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:418)
at org.junit.vintage.engine.VintageTestEngine.executeAllChildren(VintageTestEngine.java:80)
at org.junit.vintage.engine.VintageTestEngine.execute(VintageTestEngine.java:71)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:220)
at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$6(DefaultLauncher.java:188)
at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:202)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:181)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:128)
at org.eclipse.jdt.internal.junit5.runner.JUnit5TestReference.run(JUnit5TestReference.java:89)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:541)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:763)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:463)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:209)

编辑2: 我删除了doAnswer,发现以下两个语句也抛出NPE。

Mockito.doNothing().when( docProcessingService ).persistAndModify( any(), any(), any() );

verify( docProcessingService, times( 1 ) ).persistAndModify( any(), DocumentStatus.FAILED, any() );

所以我认为这与 void 返回类型有关,而不是 doAnswer()

来自相同依赖项的以下语句可以正常工作,没有任何问题。

        when( docProcessingService.publishDocumentReqMeta( any(), any() ) ).thenReturn( true );

以下是相同的方法签名,

public boolean publishDocumentReqMeta( DocumentRequest docRequest, APIKeyConfigurationVO apiKeyConfiguration )

最佳答案

I don't want to execute the complete method. But just set the status of documentRequest to documentStatus. Is this possible using junit mockito?

不,不是,因为这不是您想要做的。您想要测试该方法是否执行了它应该执行的所有操作,即更新请求状态 persistResponse

如果您想单独测试它们,请创建单独的方法。您还可以考虑将持久部分拆分为一个完全独立的类,如下所示

class DocumentProcessingService {
    private Persistor persistor;
    public void persistAndModify( DocumentRequest documentRequest, DocumentStatus     documentStatus, int timeToLive ) {
        documentRequest.getStatus() );
        documentRequest.setStatus( documentStatus.getStatus() );
        persistor.persistResponse( documentRequest.getDocumentId(), documentRequest, timeToLive );
        documentRequest.getDocumentId() );
    }
}

然后您可以通过以下方式进行测试

@RunWith(MockitoJUnitRunner.class)
class ProcessingServiceTest {
    @InjectMocks private DocumentProcessingService sut;
    @Mock private Persistor persistor;

    @Test
    public void testPersistAndModify() {
        DocumentRequest request = mock(DocumentRequest.class);
        when(request.getDocumentId()).thenReturn(id);
        DocumentStatus status = mock(DocumentStatus.class);
        when(status.getStatus).thenReturn(someStatus);

        sut.persistAndModify(request, status, x);

        // check status was updated
        verify(documentRequest).setStatus(someStatus);
        // check document was persisted
        verify(persistor).persistResponse(id, request, x);
    }
}

您的实际 persistResponse 代码很可能会执行此操作,因此您无需重构即可验证是否发生了这种情况。

编辑:

您编辑后,我不会更新上面的代码,您必须自己替换相应的代码片段。简而言之,您必须模拟 docEventLogger.logDocIdEventpreprocessorApiService.preProcess 调用。

最大的问题是“从云端下载”部分,您可能还想将该代码移动到外部类中,以便您也可以模拟该下载部分。

关于java - Mock方法实现Junit mockito,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60737932/

相关文章:

java - 在外部提供一个 for 循环的变量。这怎么可能?

java.lang.IllegalStateException : calling verify is not allowed in record state in easymock

eclipse - 用于eclipse ganymede的js测试驱动插件

使用两个模拟对象进行 Python 单元测试,如何验证调用顺序?

c# - 在模拟上为所有方法设置默认值以引发异常

java - Jackson Unmarshalling 未提供的值

Java:在每个数组值前面输入一个数字

Intellij IDEA 中的 Java 11 JShell

java - ModelJUnit运行测试一段时间

.net-4.0 - 动态对象 : is this a good solution for mocking?