如何将 Mono 错误与 Java 中的字符串进行比较 [英] How to compare Mono error to a String in Java
问题描述
我有一个类似这样的方法:
I have a method something like this :
public Mono<SomeDTO> DoAction(SomeDTO someDTOObject) {
return findUser(someDTOObject.getUsername())
.flatMap(existingUser -> {
Update update = new Update();
return mongoTemplate.upsert(
Query.query(Criteria.where("username").is(someDTOObject.getUsername())),
update,
SomeDTO.class,
COLLECTION_NAME);
}).switchIfEmpty(
Mono.defer(() -> {
return Mono.error(new Exception("User Name doesn't exist."));
})
);
}
为此,我写了一个这样的测试用例来测试异常:
For this, I have wriiten a testcase like this to test exception :
@Test
public void DoAction_TestException() {
SomeDTO someDTOObject = databaseUtil.SomeDTOMock;
Query query = Query.query(Criteria.where("username").regex("^"+userId+"$","i"));
doReturn(Mono.empty()).when(mongoTemplate).findOne(query,
SomeDTO.class, "COLLECTION_NAME");
try {
SomeDTO someDTOObjectResult = mongoImpl.DoAction(someDTOObject).block();
}
catch (Exception e) {
String expected = "User Name doesn't exist.";
String result = e.getMessage().toString(); /////// this value during debugging is "java.lang.Exception:User Name doesn't exist. "
assertEquals(expected,result);
}
}
当我运行上面的代码时,断言失败了,因为变量结果有额外的字符串.如何从结果中删除 java.lang.Exception ?
我不想使用任何字符串函数来删除部分字符串.任何帮助都会非常有帮助.
When I run the above code , the assert is failing becuase variable result has extra string along with it. How can I remove java.lang.Exception from the result ?
I dont want to use any string functions to remove part of string.ANy help would be very helpful.
推荐答案
Eugene 的回答已经向您展示了正确的方法.
Eugene's answer is already showing you the correct way.
替代解决方案 #1:
创建特定的异常类:EntityNotFoundException extends IOException
或 UsernameNotFoundException extends IOException
并测试您的结果是否是该类的实例.
Create a specific Exception class: EntityNotFoundException extends IOException
or UsernameNotFoundException extends IOException
and test if your result is an instance of that class.
替代解决方案 #2:
将您期望的字符串 expected 扩展到您真正得到的字符串.
Extend your expected String expected to the String you really get.
替代解决方案 #3:
(我不知道 Mono,所以如果 :) 如果 Mono 将异常包装到另一个异常中,您可能可以使用 e.getCause
到达原始异常:将您的行 String result = e.getMessage().toString();
更改为 String result = e.getCause().getMessage();
.
(I do not know Mono, so IF:) If Mono wraps up the Exception into another exception, you probably can reach that original exception by using e.getCause
: Change your line String result = e.getMessage().toString();
to String result = e.getCause().getMessage();
.
为了帮助我们找到这一点,只需在您的行 String expected = "User Name does not exist." 之后添加
,然后向我们展示打印了什么错误消息.从那时起,如果其他解决方案还没有帮助,我们可以进一步提供帮助.e.printStackTrace();
行.;
To help us find that out, simply add the line e.printStackTrace();
right after your line String expected = "User Name doesn't exist.";
, and then show us what error message was printed. From there on we can help further, if the other solutions have not helped yet.
这篇关于如何将 Mono 错误与 Java 中的字符串进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!