Best junit code snippet using org.junit.rules.ExpectedException.handleAssertionErrors
org.junit.rules.ExpectedException
The ExpectedException is a rule which helps scripts to verify that the script throws the specific exception or not
Here are code snippets that can help you understand more how developers are using
Source: BddIntegrationTest.java
...13 * @author Lovro Pandzic14 */15public class BddIntegrationTest {16 @Rule17 public ExpectedException expectedException = ExpectedException.none().handleAssertionErrors();18 private ClassUnderTest classUnderTest = new ClassUnderTest();19 @Test20 public void shouldPassWhenExpectedExceptionIsThrown() throws Exception {21 when(() -> classUnderTest.throwsA(new Exception())).thenChecked(e -> assertThat(e, isA(Exception.class)));22 }23 @Test24 public void shouldFailWhenWrongExceptionIsThrown() throws Exception {25 expectedException.handleAssertionErrors();26 expectedException.expect(AssertionError.class);27 when(() -> classUnderTest.throwsA(new IOException())).then(e -> assertThat(e,28 is(instanceOf(NullPointerException29 .class))));30 }31 @Test32 public void shouldPassWhenReturnsExpectedObject() {33 Object value = new Object();34 when(classUnderTest.returnsA(value)).then(actual -> assertThat(actual, is(equalTo(value))));35 }36 @Test37 public void simpleLambdaThrowTest() throws Exception {38 when(() -> {39 throw new Exception();40 }).thenChecked(e -> assertThat(e, isA(Exception.class)));41 }42 @Test43 public void simpleLambdaReturnTest() {44 when(new Object()).then(actual -> assertThat(actual, isA(Object.class)));45 }46 @Test(expected = Exception.class)47 public void shouldFailWhenValueProviderThrowsAUncheckedException() throws Exception {48 when(classUnderTest.throwsA(new Exception()));49 }50 @Test51 public void shouldFailWhenExceptionProviderThrowsAUncheckedException() throws Exception {52 expectedException.expect(isA(Exception.class));53 when(() -> classUnderTest.throwsA(new Exception())).thenShouldNotThrow();54 }55 @Test56 public void shouldFailWhenReturnsOneObjectButExpectsDifferentObject() {57 expectedException.handleAssertionErrors();58 expectedException.expect(AssertionError.class);59 expectedException.expectMessage("is <java.lang.Object");60 expectedException.expectMessage("but: was");61 Object value = new Object();62 when(classUnderTest.returnsA(value)).then(actual -> assertThat(actual, is(equalTo(new Object()))));63 }64 @Test65 public void shouldFailOnFirstWhenWhenTwoWhensFail() {66 expectedException.expect(isA(IOException.class));67 when(() -> classUnderTest.throwsA(new IOException()));68 when(() -> classUnderTest.throwsA(new Exception()));69 }70 @Test71 public void shouldFailWithUnexpectedExceptionForWrongCheckedException() {...
Source: ExpectedException.java
...15import org.junit.runners.model.Statement;16public class ExpectedException17implements TestRule {18 private final ExpectedExceptionMatcherBuilder fMatcherBuilder = new ExpectedExceptionMatcherBuilder();19 private boolean handleAssertionErrors = false;20 private boolean handleAssumptionViolatedExceptions = false;21 private ExpectedException() {22 }23 private void failDueToMissingException() throws AssertionError {24 String string2 = StringDescription.toString(this.fMatcherBuilder.build());25 Assert.fail("Expected test to throw " + string2);26 }27 private void handleException(Throwable throwable) throws Throwable {28 if (this.fMatcherBuilder.expectsThrowable()) {29 Assert.assertThat(throwable, this.fMatcherBuilder.build());30 return;31 }32 throw throwable;33 }34 public static ExpectedException none() {35 return new ExpectedException();36 }37 private void optionallyHandleException(Throwable throwable, boolean bl2) throws Throwable {38 if (bl2) {39 this.handleException(throwable);40 return;41 }42 throw throwable;43 }44 @Override45 public Statement apply(Statement statement, Description description) {46 return new ExpectedExceptionStatement(statement);47 }48 public void expect(Class<? extends Throwable> class_) {49 this.expect(CoreMatchers.instanceOf(class_));50 }51 public void expect(Matcher<?> matcher) {52 this.fMatcherBuilder.add(matcher);53 }54 public void expectCause(Matcher<? extends Throwable> matcher) {55 this.expect(ThrowableCauseMatcher.hasCause(matcher));56 }57 public void expectMessage(String string2) {58 this.expectMessage(CoreMatchers.containsString(string2));59 }60 public void expectMessage(Matcher<String> matcher) {61 this.expect(ThrowableMessageMatcher.hasMessage(matcher));62 }63 public ExpectedException handleAssertionErrors() {64 this.handleAssertionErrors = true;65 return this;66 }67 public ExpectedException handleAssumptionViolatedExceptions() {68 this.handleAssumptionViolatedExceptions = true;69 return this;70 }71 private class ExpectedExceptionStatement72 extends Statement {73 private final Statement fNext;74 public ExpectedExceptionStatement(Statement statement) {75 this.fNext = statement;76 }77 @Override78 public void evaluate() throws Throwable {79 try {80 this.fNext.evaluate();81 if (ExpectedException.this.fMatcherBuilder.expectsThrowable()) {82 ExpectedException.this.failDueToMissingException();83 }84 return;85 }86 catch (AssumptionViolatedException var1_1) {87 ExpectedException.this.optionallyHandleException(var1_1, ExpectedException.this.handleAssumptionViolatedExceptions);88 return;89 }90 catch (AssertionError var1_2) {91 ExpectedException.this.optionallyHandleException((Throwable)((Object)var1_2), ExpectedException.this.handleAssertionErrors);92 return;93 }94 catch (Throwable var1_3) {95 ExpectedException.this.handleException(var1_3);96 return;97 }98 }99 }100}...
Source: ThreeTenBaseTest.java
...18public class ThreeTenBaseTest {19 @Rule20 public ExpectedException thrown = none();21 protected void expectException(Class<? extends Throwable> type, String message) {22 thrown.handleAssertionErrors();23 thrown.expect(type);24 thrown.expectMessage(message);25 }26 27 protected void expectIllegalArgumentException(String message) {28 expectException(IllegalArgumentException.class, message);29 }30 public void failBecauseExpectedAssertionErrorWasNotThrown() {31 Assert.fail("Assertion error expected");32 }33}...
handleAssertionErrors
Using AI Code Generation
1import org.junit.Rule;2import org.junit.Test;3import org.junit.rules.ExpectedException;4import static org.junit.Assert.assertEquals;5import static org.junit.Assert.fail;6public class TestJUnit4 {7 public ExpectedException thrown = ExpectedException.none();8 public void throwsNothing() {9 }10 public void throwsNullPointerException() {11 thrown.expect(NullPointerException.class);12 throw new NullPointerException();13 }14 public void throwsNullPointerExceptionWithMessage() {15 thrown.expect(NullPointerException.class);16 thrown.expectMessage("happened");17 thrown.reportMissingExceptionWithMessage("Expected NullPointerException to be thrown with message a string containing \"happened\"");18 throw new NullPointerException("something happened");19 }20 public void test() {21 try {22 throw new NullPointerException();23 } catch (NullPointerException e) {24 assertEquals("NullPointerException", e.getClass().getSimpleName());25 }26 }27 public void test2() {28 try {29 throw new NullPointerException();30 } catch (NullPointerException e) {31 assertEquals("NullPointerException", e.getClass().getSimpleName());32 return;33 }34 fail("Should have thrown an exception");35 }36}37The test() method is almost the same as the test2() method. The difference is that in the test() method, the catch
handleAssertionErrors
Using AI Code Generation
1import org.junit.Test;2import org.junit.Rule;3import org.junit.rules.ExpectedException;4public class TestException {5 public ExpectedException thrown = ExpectedException.none();6 public void throwsNothing() {7 }8 public void throwsNullPointerException() {9 thrown.expect(NullPointerException.class);10 throw new NullPointerException();11 }12 public void throwsIllegalArgumentException() {13 thrown.expect(IllegalArgumentException.class);14 throw new IllegalArgumentException();15 }16 public void throwsNullPointerExceptionWithMessage() {17 thrown.expect(NullPointerException.class);18 thrown.expectMessage("Hello");19 throw new NullPointerException("Hello");20 }21 public void throwsNullPointerExceptionWithMessageContaining() {22 thrown.expect(NullPointerException.class);23 thrown.expectMessage("Hello");24 throw new NullPointerException("Hello World");25 }26 public void throwsNullPointerExceptionWithMessageMatching() {27 thrown.expect(NullPointerException.class);28 thrown.expectMessage(".*H.llo.*");29 throw new NullPointerException("Hello World");30 }31 public void throwsNullPointerExceptionWithCause() {32 NullPointerException cause = new NullPointerException("Hello");33 thrown.expect(IllegalArgumentException.class);34 thrown.expectCause(is(cause));35 throw new IllegalArgumentException(cause);36 }37 public void throwsNullPointerExceptionWithCauseContaining() {38 NullPointerException cause = new NullPointerException("Hello");39 thrown.expect(IllegalArgumentException.class);40 thrown.expectCause(is(cause));41 throw new IllegalArgumentException(new NullPointerException("Hello World"));42 }43 public void throwsNullPointerExceptionWithCauseMatching() {44 NullPointerException cause = new NullPointerException("Hello");45 thrown.expect(IllegalArgumentException.class);46 thrown.expectCause(is(cause));47 throw new IllegalArgumentException(new NullPointerException("Hello World"));48 }49}
handleAssertionErrors
Using AI Code Generation
1import static org.junit.Assert.assertEquals;2import static org.junit.Assert.assertTrue;3import org.junit.Rule;4import org.junit.Test;5import org.junit.rules.ExpectedException;6public class ExpectedExceptionTest {7 public ExpectedException thrown = ExpectedException.none();8 public void throwsNothing() {9 }10 public void throwsNullPointerException() {11 thrown.expect(NullPointerException.class);12 throw new NullPointerException();13 }14 public void throwsNullPointerExceptionWithMessage() {15 thrown.expect(NullPointerException.class);16 thrown.expectMessage("happened");17 throw new NullPointerException("something happened");18 }19 public void throwsArithmeticExceptionWithMessage() {20 thrown.expect(ArithmeticException.class);21 thrown.expectMessage("/ by zero");22 int i = 1 / 0;23 }24 public void throwsArithmeticExceptionWithMessage2() {25 thrown.expect(ArithmeticException.class);26 thrown.expectMessage("/ by zero");27 thrown.expectMessage("second message");28 int i = 1 / 0;29 }30 public void throwsArithmeticExceptionWithMessage3() {31 thrown.expect(ArithmeticException.class);32 thrown.expectMessage("/ by zero");33 thrown.expectMessage("second message");34 int i = 1 / 0;35 }36 public void throwsArithmeticExceptionWithMessage4() {37 thrown.expect(ArithmeticException.class);38 thrown.expectMessage("/ by zero");39 thrown.expectMessage("second message");40 int i = 1 / 0;41 }42 public void throwsArithmeticExceptionWithMessage5() {43 thrown.expect(ArithmeticException.class);44 thrown.expectMessage("/ by zero");45 thrown.expectMessage("second message");46 int i = 1 / 0;47 }48 public void throwsArithmeticExceptionWithMessage6() {49 thrown.expect(ArithmeticException.class);50 thrown.expectMessage("/ by zero");51 thrown.expectMessage("second message");52 int i = 1 / 0;53 }54 public void throwsArithmeticExceptionWithMessage7() {55 thrown.expect(ArithmeticException.class);56 thrown.expectMessage("/ by zero");57 thrown.expectMessage("second message");
handleAssertionErrors
Using AI Code Generation
1[INFO] [ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project junit4: Compilation failure: Compilation failure:2[INFO] [ERROR] symbol: method handleAssertionErrors()3[INFO] [ERROR] symbol: method handleAssertionErrors()4[INFO] [ERROR] symbol: method handleAssertionErrors()5[INFO] [ERROR] symbol: method handleAssertionErrors()6[INFO] [ERROR] symbol: method handleAssertionErrors()7[INFO] [ERROR] symbol: method handleAssertionErrors()
handleAssertionErrors
Using AI Code Generation
1import org.junit.Test;2import org.junit.rules.ExpectedException;3import static org.junit.Assert.assertEquals;4import static org.junit.Assert.fail;5public class ExceptionTest {6 public void testExceptionMessage() {7 try {8 throw new IllegalArgumentException("a message");9 } catch (IllegalArgumentException e) {10 assertEquals("a message", e.getMessage());11 }12 }13 public void testExceptionMessageWithRule() {14 ExpectedException thrown = ExpectedException.none();15 thrown.expect(IllegalArgumentException.class);16 thrown.expectMessage("a message");17 throw new IllegalArgumentException("a message");18 }19}20at org.junit.Assert.assertEquals(Assert.java:115)21at org.junit.Assert.assertEquals(Assert.java:144)22at com.baeldung.junit.exception.ExceptionTest.testExceptionMessage(ExceptionTest.java:11)23at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)24at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)25at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)26at java.lang.reflect.Method.invoke(Method.java:498)27at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)28at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)29at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)30at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)31at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)32at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)33at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)34at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)35at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)36at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)37at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)38at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)39at org.junit.runners.ParentRunner.run(ParentRunner.java:363)40at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
handleAssertionErrors
Using AI Code Generation
1 public ExpectedException thrown = ExpectedException.none();2 public void testException() {3 thrown.expect(IllegalArgumentException.class);4 thrown.expectMessage("Negative value not allowed");5 MathUtils.divide(1, -1);6 }7 @Test(expected = IllegalArgumentException.class)8 public void testException2() {9 MathUtils.divide(1, -1);10 }11 public void testException3() {12 try {13 MathUtils.divide(1, -1);14 fail("Expected an IllegalArgumentException to be thrown");15 } catch (IllegalArgumentException anException) {16 assertThat(anException.getMessage(), is("Negative value not allowed"));17 }18 }19 public void testException4() {20 try {21 MathUtils.divide(1, 0);22 fail("Expected an ArithmeticException to be thrown");23 } catch (ArithmeticException anException) {24 assertThat(anException.getMessage(), is("Division by zero"));25 }26 }27}
powermock mocking constructor via whennew() does not work with anonymous class
How do you assert that a certain exception is thrown in JUnit tests?
How to assertThat String is not empty
'No JUnit tests found' in Eclipse
java.util.MissingResourceException: Can't find bundle for base name javax.servlet.LocalStrings, locale es_ES
Naming convention JUnit suffix or prefix Test
Is org.junit.Assert.assertThat better than org.hamcrest.MatcherAssert.assertThat?
Debugging Spring configuration
How to use Mockito with JUnit5
Populating Spring @Value during Unit Test
You need to have prepared the class calling the constructor, not the class on which the constructor is called, the following should fix you up:
@PrepareForTest(DummyTarget.class)
For more information check this page.
Check out the latest blogs from LambdaTest on this topic:
This article is a part of our Content Hub. For more in-depth resources, check out our content hub on A Detailed TestNG Tutorial.
A framework is a collection or set of tools and processes that work together to support testing and developmental activities. It contains various utility libraries, reusable modules, test data setup, and other dependencies. Be it web development or testing, there are multiple frameworks that can enhance your team’s efficiency and productivity. Web testing, in particular, has a plethora of frameworks, and selecting a framework that suits your needs depends on your language of choice.
Automation testing has become an absolute necessity in an agile and fast-paced business environment with an immense focus on accelerated time to market. However, as far as automation is concerned, Selenium automation testing still reaps the maximum benefits in terms of test coverage and browser coverage.
This article is a part of our Content Hub. For more in-depth resources, check out our content hub on Selenium NUnit Tutorial.
Hey Testers! Hope you are staying safe and healthy. In these turbulent times, it is evident that organizations need robust and scalable functional capabilities to keep their businesses thriving even when confronted with imminent workplace challenges. We at LambdaTest believe that repetitive aspects of testing should be eliminated using smart solutions.
LambdaTest also has a detailed JUnit tutorial explaining its features, importance, advanced use cases, best practices, and more to help you get started with running your automation testing scripts.
Here are the detailed JUnit testing chapters to help you get started:
You can also check out our JUnit certification if you wish to take your career in Selenium automation testing with JUnit to the next level.
Get 100 minutes of automation test minutes FREE!!