How to force a method to throw an Exception in jUnit testing?
You need to first mock the class containing selectSomethingBySomething()
and then record this behavior. In mockito you'll say:
SomeDao someDaoMock = mock(SomeDao.class);
willThrow(new SQLException())).given(someDaoMock).selectSomethingBySomething();
Then inject someDaoMock
into your class under test and when it calls someDaoMock.selectSomethingBySomething()
it'll throw previously chosen exception.
JUnit Test : Forcing exception from internal method call
As you suggested, Mockito would be a classic tool for such a usecase:
// Initialization - should probably be in the @Before method:
A a = Mockito.spy(new A());
Mockito.doThrow(new SomeException("yay!")).when(a).m2();
// Actual test:
SomeResult actualResult = a.m1();
assertEquals(someExpectedResult, actualResult); // or some other assertion
The above snippet creates a spy
ied object (think of it as an anonymous class that extends A
) with the defined behavior that when m2()
is called, a SomeException
will be thrown.
Then the code goes on to call the real m1()
method, which itself calls m2()
, and has to handle the exception.
Junit Force to throw Exception on method call
When writing spring-boot integration test you should inject the mock beans using @MockBean annotation
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
Class ATest {
@Autowired
private A obj;
@MockBean
private SimpleJdbcCall simpleJdbcCall;
@Test
public void throwExceptionFromMethod() {
try {
Mockito.when(simpleJdbcCall.withProcedureName(Mockito.anyString())).thenReturn(simpleJdbcCall);
Mockito.when(simpleJdbcCall.declareParameters(Mockito.any())).thenReturn(simpleJdbcCall);
Mockito.doThrow(new RuntimeException()).when(simpleJdbcCall).execute(
ArgumentMatchers.any(SqlParameterSource.class));
//or you can use thenThrow also
Mockito.when(simpleJdbcCall.execute(ArgumentMatchers.any(SqlParameterSource.class))).thenThrow(RuntimeException.class);
final int message = obj.mymeth(modifyLeadDispositionRequest);
} catch (Exception e) {
e.printStackTrace();
// just to assert here
}
}
}
You can a follow some of the examples here for testing exceptions in junit4 or junit5
How do you assert that a certain exception is thrown in JUnit tests?
It depends on the JUnit version and what assert libraries you use.
- For JUnit5 and 4.13 see answer https://stackoverflow.com/a/2935935/2986984
- If you use assertJ or google-truth, see answer https://stackoverflow.com/a/41019785/2986984
The original answer for JUnit <= 4.12
was:
@Test(expected = IndexOutOfBoundsException.class)
public void testIndexOutOfBoundsException() {
ArrayList emptyList = new ArrayList();
Object o = emptyList.get(0);
}
Though answer https://stackoverflow.com/a/31826781/2986984 has more options for JUnit <= 4.12.
Reference :
- JUnit Test-FAQ
How to simulate throwing an exception only once in retry with JUnit/Mockito test?
According to the Mockito documentation you can set different behavior for consecutive method calls.
when(mock.someMethod("some arg"))
.thenThrow(new RuntimeException())
.thenReturn("foo");
In case of a void method you can do something similar (Mockito documentation)
doThrow(new RuntimeException())
.doNothing()
.when(mock).doSomething();
how to test that a method throws an exception junit5
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());
}
Related Topics
How to Upload a File and Json Data in Postman
Resttemplate: How to Send Url and Query Parameters Together
How to Click an Li Inside a Ul Using Selenium Webdriver
How to Display Auto-Configuration Report When Running a Spring Boot Application
Jpa:How to Convert a Native Query Result Set to Pojo Class Collection
Javax.Validation - Allow Null But Validate If the Value Is Not
Spring Boot/Spring Kafka Ssl Configuration by Environment Variables Impossible
Mockito How to Mock Only the Call of a Method of the Superclass
The Group Coordinator Is Not Available-Kafka
Multipartexception: Current Request Is Not a Multipart Request
Cannot Construct Instance of 'Java.Time.Localdate' - Spring Boot, Elasticseach, Jackson
How to Check Whether Kafka Server Is Running
How to Convert a One-Dimensional Array to Two-Dimensional Array in Java
Serialize a Double to 2 Decimal Places Using Jackson
Junit 5 - No Parameterresolver Registered for Parameter
String.Replaceall Single Backslashes With Double Backslashes