gpt4 book ai didi

java - Mockito 中的单元测试,在对象上调用函数链?

转载 作者:行者123 更新时间:2023-12-01 17:50:58 25 4
gpt4 key购买 nike

我没有在 Mockito 中进行太多测试,而且测试也非常少。当我对某个对象调用删除时,我得到一个DeleteResponse。它有一个名为 getProcessingErrors() 的方法,它是一个集合。然后我可以调用 .isEmpty() 来查看是否有错误。我正试图 mock 这一点。

DeleteResponse deleteResponse = mock(DeleteResponse.class);

when(catalogFramework.delete(any(DeleteRequest.class))).thenReturn(deleteResponse);

when(deleteResponse.getProcessingErrors()).thenReturn(new HashSet<ProcessingDetails>());

PowerMockito.when(deleteResponse.getProcessingErrors().isEmpty()).thenReturn(true);

错误:

org.mockito.exceptions.misusing.WrongTypeOfReturnValue: 
Boolean cannot be returned by getProcessingErrors()
getProcessingErrors() should return Set
***
If you're unsure why you're getting above error read on.
Due to the nature of the syntax above problem might occur because:
1. This exception *might* occur in wrongly written multi-threaded tests.
Please refer to Mockito FAQ on limitations of concurrency testing.
2. A spy is stubbed using when(spy.foo()).then() syntax. It is safer to stub spies -
- with doReturn|Throw() family of methods. More in javadocs for Mockito.spy() method.

现在,从我阅读本文的方式来看,它说 isEmpty 无法返回 boolean 值,但我相信它很早就被删除了,只是查看 getProcessingErrors。我该如何解决这个问题?

最佳答案

在模拟 isEmpty() 函数之前,您需要模拟 deleteResponse.getProcessingErrors() 对象

when(deleteResponse.getProcessingErrors()).thenReturn(mockObject);
PowerMockito.when(mockObject.isEmpty()).thenReturn(true);

关于java - Mockito 中的单元测试,在对象上调用函数链?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50168721/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com