how to test that a method throws an exception junit5 [duplicate]

Multi tool use
Multi tool use


how to test that a method throws an exception junit5 [duplicate]



This question already has an answer here:



I have a DocumentTypeDetector class that has a detectForRequest() method.
I'm doing the corresponding tests, but I have not been able to verify that a customized exception is thrown, I'm using JUNIT 5.


DocumentTypeDetector


detectForRequest()



I have reviewed here, but the answers have not helped me, this is the code I have written following an example:


@Test
public void tryThrowExceptionForInvalidRequest() throws Exception{

InvalidInputRequestType exceptionThrown = Assertions.assertThrows(
InvalidInputRequestType.class,
() -> {
throw new InvalidInputRequestType("La petición debe estar en un formato valido JSON o XML");
}
);
assertEquals("La petición debe estar en un formato valido JSON o XML", exceptionThrown.getMessage());
}



But this does not tell me anything about my test



I need to verify that my method returns the corresponding exception, something like this:


@Test
public void tryThrowExceptionForInvalidRequest() throws Exception{
String invalid = "Este es un request invalido";
assertIsThrown(InvalidInputRequestType.class, detector.detectForRequest(invalid));
}



How can I test this?



This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.




1 Answer
1



Maybe you can try the following code:


@Test
public void tryThrowExceptionForInvalidRequest() throws Exception {

final String invalid = "Este es un request invalido";

InvalidInputRequestType exceptionThrown = Assertions.assertThrows(
InvalidInputRequestType.class,
() -> {
detector.detectForRequest(invalid);
}
);
assertEquals(invalid, exceptionThrown.getMessage());
}

tz3DrUb
1YuSSYsQMO

Popular posts from this blog

Rothschild family

Cinema of Italy