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);
}
}
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's answer is already showing you the correct way.
Alternate Solution #1:
Create a specific Exception class: EntityNotFoundException extends IOException
or UsernameNotFoundException extends IOException
and test if your result is an instance of that class.
Alternate Solution #2:
Extend your expected String expected to the String you really get.
Alternate Solution #3:
(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();
.
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.