我正在为一个应用程序类编写单元测试用例。由于该类中的所有代码都是用java8编写的,因此很难为它编写测试用例。我坚持需要模拟方法链接的情况。
@Override
public Single<MetadataManagerDeleteAttributeResponseV1> processEvent(
Context context, MetadataManagerDeleteAttributeV1 event) {
Database worldviewDatabase = context.client().database();
String primaryKey = "metadata-manager:attribute:v1.json" + SCHEMA_CONNECTOR + event.getId();
System.out.println(worldviewDatabase.deleteOne(primaryKey, WriteContext.builder().build()).map(deleteResultTry->deleteResultTry.get().ids()));
//database object is of type single<try<deleteTry>>>
return worldviewDatabase
.deleteOne(primaryKey, WriteContext.builder().build())
.map(deleteResultTry -> handleResponse(deleteResultTry, primaryKey))
.map(Try::get);
}
public Try<MetadataManagerDeleteAttributeResponseV1> handleResponse(
Try<DeleteResult> result, String primaryKey) {
return result
.filter(res -> !res.ids().isEmpty())
.flatMap(res -> Try.fromOptional(res.ids().stream().findFirst()))
.map(id -> {
var response = new MetadataManagerDeleteAttributeResponseV1();
return response.withId(id.split(SCHEMA_CONNECTOR)[1]);
}).mapException(e -> handleError(e, primaryKey));
}
private HttpCodedException handleError(Throwable error, String primaryKey) {
if (error instanceof NoSuchElementException) {
logger.warn("DeleteAttributeMetadataManagerV1Handler: object with " + primaryKey + " does not exist");
return new HttpCodedException(HandlerErrorCode._404_NOT_FOUND,
"object with " + primaryKey + " does not exist");
} else {
logger.error("DeleteAttributeMetadataManagerV1Handler error occurs: " + error.getMessage());
return new HttpCodedException(HandlerErrorCode._500_INTERNAL_SERVER_ERROR, "error occurs during"
+ " deleting object with " + primaryKey + ": " + error.getMessage());
}
}
我不知道如何模拟以下代码行
return worldviewDatabase
.deleteOne(primaryKey, WriteContext.builder().build())
.map(deleteResultTry -> handleResponse(deleteResultTry, primaryKey))
.map(Try::get);
我想知道我可以采用哪种方法来模拟链接到一个陈述中的所有方法。
谢谢
答案 0 :(得分:2)
您需要将方法链调用分为几部分。 例如:
void yourMethod(SomeObject someObject)
{
someObject.someMethod1().someMethod2().someMethod3();
}
测试:
@Mock
SomeObject someObject;
when(someObject.someMethod1()).thenReturn(someObject2);
when(someObject2.someMethod2()).thenReturn(someObject3);
when(someObject3.someMethod3()).thenReturn(someObject4);
请让我知道是否有任何疑问或问题。