I was recently asked in an interview on how can i write a junit unit test case to test for "OutOfMemoryError" and i have written the below code:-
public class OutOfMemoryError {
public static void main(String[] args) {
new OutOfMemoryError().throwError();
}
public void throwError() {
List<String> list = new ArrayList<>();
for (int i = 0;; i++)
list.add("1");
}
}
Junit Test Case:-
public class ExceptionTest {
private OutOfMemoryError outOfMemoryError;
@Before
public void init() {
outOfMemoryError = new OutOfMemoryError();
}
@After
public void tearDown() {
outOfMemoryError = null;
}
@Test(expected = Error.class)
public void testError() {
outOfMemoryError.throwError();
}
}
The Interviewer told me that the Junit test case is incorrect. Can anyone please tell me the right way of writing it?