How to use expectMessage method of org.junit.rules.ExpectedException class

Best junit code snippet using org.junit.rules.ExpectedException.expectMessage

ExpectedExceptionorg.junit.rules.ExpectedException

The ExpectedException is a rule which helps scripts to verify that the script throws the specific exception or not

Code Snippets

Here are code snippets that can help you understand more how developers are using

Source:ExpectedExceptionTest.java Github

copy

Full Screen

...120 public ExpectedException thrown = none();121 @Test122 public void throwsNullPointerExceptionWithMessage() {123 thrown.expect(NullPointerException.class);124 thrown.expectMessage(ARBITRARY_MESSAGE);125 throw new NullPointerException(ARBITRARY_MESSAGE + "something else");126 }127 }128 public static class ThrowExceptionWithWrongType {129 @Rule130 public ExpectedException thrown = none();131 @Test132 public void throwsNullPointerException() {133 thrown.expect(NullPointerException.class);134 throw new IllegalArgumentException();135 }136 }137 public static class HasWrongMessage {138 @Rule139 public ExpectedException thrown = none();140 @Test141 public void throwsNullPointerException() {142 thrown.expectMessage("expectedMessage");143 throw new IllegalArgumentException("actualMessage");144 }145 }146 public static class ThrowNoExceptionButExpectExceptionWithType {147 @Rule148 public ExpectedException thrown = none();149 @Test150 public void doesntThrowNullPointerException() {151 thrown.expect(NullPointerException.class);152 }153 }154 public static class WronglyExpectsExceptionMessage {155 @Rule156 public ExpectedException thrown = none();157 @Test158 public void doesntThrowAnything() {159 thrown.expectMessage("anything!");160 }161 }162 public static class ExpectsSubstring {163 @Rule164 public ExpectedException thrown = none();165 @Test166 public void throwsMore() {167 thrown.expectMessage("anything!");168 throw new NullPointerException(169 "This could throw anything! (as long as it has the right substring)");170 }171 }172 public static class ExpectsSubstringNullMessage {173 @Rule174 public ExpectedException thrown = none();175 @Test176 public void throwsMore() {177 thrown.expectMessage("anything!");178 throw new NullPointerException();179 }180 }181 public static class ExpectsMessageMatcher {182 @Rule183 public ExpectedException thrown = none();184 @Test185 public void throwsMore() {186 thrown.expectMessage(startsWith(ARBITRARY_MESSAGE));187 throw new NullPointerException(ARBITRARY_MESSAGE + "!");188 }189 }190 public static class ExpectedMessageMatcherFails {191 @Rule192 public ExpectedException thrown = none();193 @Test194 public void throwsMore() {195 thrown.expectMessage(equalTo("Wrong start"));196 throw new NullPointerException("Back!");197 }198 }199 public static class ExpectsMatcher {200 @Rule201 public ExpectedException thrown = none();202 @Test203 public void throwsMore() {204 thrown.expect(any(Exception.class));205 throw new NullPointerException("Ack!");206 }207 }208 public static class ExpectsMultipleMatchers {209 @Rule210 public ExpectedException thrown = none();211 @Test212 public void throwsMore() {213 thrown.expect(IllegalArgumentException.class);214 thrown.expectMessage("Ack!");215 throw new NullPointerException("Ack!");216 }217 }218 //https://github.com/junit-team/junit4/pull/583219 public static class ExpectAssertionErrorWhichIsNotThrown {220 @Rule221 public ExpectedException thrown = none();222 @Test223 public void fails() {224 thrown.expect(AssertionError.class);225 }226 }227 public static class FailBeforeExpectingException {228 @Rule229 public ExpectedException thrown = none();230 @Test231 public void fails() {232 fail(ARBITRARY_MESSAGE);233 thrown.expect(IllegalArgumentException.class);234 }235 }236 public static class FailedAssumptionAndExpectException {237 @Rule238 public ExpectedException thrown = none();239 @Test240 public void failedAssumption() {241 assumeTrue(false);242 thrown.expect(NullPointerException.class);243 }244 }245 public static class ThrowExceptionWithMatchingCause {246 @Rule247 public ExpectedException thrown = none();248 @Test249 public void throwExceptionWithMatchingCause() {250 NullPointerException expectedCause = new NullPointerException("expected cause");251 thrown.expect(IllegalArgumentException.class);252 thrown.expectMessage("Ack!");253 thrown.expectCause(is(expectedCause));254 throw new IllegalArgumentException("Ack!", expectedCause);255 }256 }257 public static class ThrowExpectedNullCause {258 @Rule259 public ExpectedException thrown = none();260 @Test261 public void throwExpectedNullCause() {262 thrown.expect(IllegalArgumentException.class);263 thrown.expectMessage("Ack!");264 thrown.expectCause(nullValue(Throwable.class));265 throw new IllegalArgumentException("Ack!");266 }267 }268 public static class ThrowUnexpectedCause {269 @Rule270 public ExpectedException thrown = ExpectedException.none();271 @Test272 public void throwWithCause() {273 thrown.expect(IllegalArgumentException.class);274 thrown.expectMessage("Ack!");275 thrown.expectCause(is(new NullPointerException("expected cause")));276 throw new IllegalArgumentException("Ack!", new NullPointerException("an unexpected cause"));277 }278 }279 280 public static class UseNoCustomMessage {281 @Rule282 public ExpectedException thrown= ExpectedException.none();283 @Test284 public void noThrow() {285 thrown.expect(IllegalArgumentException.class);286 }287 }288 public static class UseCustomMessageWithPlaceHolder {...

Full Screen

Full Screen

Source:ServerProcessImplTest.java Github

copy

Full Screen

...60 public void can_not_start_twice() throws Exception {61 prepareValidCommand("com.sonar.orchestrator.echo.SonarQubeEmulator");62 underTest.start();63 try {64 expectedException.expectMessage("Server is already started");65 expectedException.expect(IllegalStateException.class);66 underTest.start();67 } finally {68 underTest.stop();69 }70 }71 @Test72 public void can_stop_if_not_started() throws Exception {73 prepareValidCommand("com.sonar.orchestrator.echo.SonarQubeEmulator");74 underTest.start();75 underTest.stop();76 // following stops do not fail77 underTest.stop();78 underTest.stop();79 }80 @Test81 public void fail_if_command_can_not_be_executed() throws Exception {82 when(server.version()).thenReturn(Version.create("6.7"));83 // execute an invalid command from an invalid directory. That should fail.84 File invalidDir = temp.newFolder();85 when(server.getHome()).thenReturn(invalidDir);86 invalidDir.delete();87 when(commandLineFactory.create(server)).thenReturn(new CommandLine("command_does_not_exist"));88 expectedException.expectMessage("Can not execute command");89 underTest.start();90 }91 @Test92 public void fail_if_server_fails_to_start() throws Exception {93 prepareValidCommand("com.sonar.orchestrator.echo.Fail");94 expectedException.expect(IllegalStateException.class);95 expectedException.expectMessage("Server startup failure");96 underTest.start();97 verify(logWatcher).isStarted("starting");98 verify(logWatcher).isStarted("error");99 underTest.stop();100 }101 @Test102 public void fail_if_server_version_is_older_than_6_2() throws Exception {103 when(server.version()).thenReturn(Version.create("5.6"));104 expectedException.expect(IllegalStateException.class);105 expectedException.expectMessage("Minimum supported version of SonarQube is 6.2. Got 5.6.");106 underTest.start();107 }108 @Test109 public void fail_on_timeout_if_process_is_alive_but_not_correctly_started() throws IOException {110 prepareValidCommand("com.sonar.orchestrator.echo.Stuck");111 underTest.setStartupTimeout(1);112 // process is stuck, force kill. Let's reduce the regular stop command to113 // 1ms so that test does not wait for 5 minutes before force the kill114 underTest.setStopTimeout(1);115 expectedException.expectMessage("Server did not start in timely fashion");116 underTest.start();117 assertThat(underTest.isProcessAlive()).isFalse();118 }119 private void prepareValidCommand(String mainClass) throws IOException {120 when(server.version()).thenReturn(Version.create("6.7"));121 when(server.getHome()).thenReturn(new File("../echo/target"));122 File jar = TestModules.getFile("../echo/target", "echo-*.jar");123 when(logWatcher.isStarted("started")).thenReturn(true);124 when(commandLineFactory.create(server)).thenReturn(125 new CommandLine("java")126 .addArgument("-cp")127 .addArgument(jar.getCanonicalPath())128 .addArgument(mainClass)129 );...

Full Screen

Full Screen

Source:ExpectedException.java Github

copy

Full Screen

...32 // This one saves a little typing :-)33 public void expect( Class<? extends Throwable> type, String substringOfMessage )34 {35 expect( type );36 expectMessage( substringOfMessage );37 }38 public void expectAssertionError( String message )39 {40 expect( AssertionError.class );41 expectMessage( message );42 }43 public void expectNullPointerException( String message )44 {45 expect( NullPointerException.class );46 expectMessage( message );47 }48 public void expect( Throwable error )49 {50 expect( error.getClass() );51 expectMessage( error.getMessage() );52 }53 public void expect( Class<? extends Throwable> type )54 {55 delegate.expect( type );56 }57 public void expectMessage( String message )58 {59 delegate.expectMessage( message );60 }61}

Full Screen

Full Screen

Source:TestRulesDemo.java Github

copy

Full Screen

...33 customer.setCustName("Tom");34 customer.setCustAddress(new Address());35 36 thrown.expect(InvalidInitialAmountException.class);37 //thrown.expectMessage("Initial Amount Should be greater than 500.");38 //thrown.expectMessage("Not Null!");39 thrown.expectMessage("Initial Amount");40 acccountService.addAccount(customer, 100);41 42 }43 44 @Rule45 public Timeout timeout=new Timeout(100);46 @Test47 public void test_myLoop(){48 49 acccountService.myLoop();50 }5152}

Full Screen

Full Screen

Source:RepeatUntilExpectedExceptionRule.java Github

copy

Full Screen

...13 Statement statement1 = createFromAnnotationWith(repeat, statement);14 Statement resultStatement = statement1 == null ? statement : statement1;15 return expectedException.apply(resultStatement, description);16 }17 public void expectMessage(Matcher<String> matcher) {18 expectedException.expectMessage(matcher);19 }20 public void expect(Class<? extends Throwable> type) {21 expectedException.expect(type);22 }23 public void expect(Matcher<?> matcher) {24 expectedException.expect(matcher);25 }26 public void expectMessage(String substring) {27 expectedException.expectMessage(substring);28 }29}...

Full Screen

Full Screen

expectMessage

Using AI Code Generation

copy

Full Screen

1package com.javacodegeeks.junit;2import org.junit.Rule;3import org.junit.Test;4import org.junit.rules.ExpectedException;5public class ExpectedExceptionTest {6 public ExpectedException thrown = ExpectedException.none();7 public void shouldTestExceptionMessage() throws IndexOutOfBoundsException {8 final String[] strArray = new String[] { "a", "b", "c" };9 thrown.expect(IndexOutOfBoundsException.class);10 thrown.expectMessage("Index: 3, Size: 3");11 final String str = strArray[3];12 }13}14 at org.junit.Assert.assertEquals(Assert.java:115)15 at org.junit.Assert.assertEquals(Assert.java:144)16 at org.junit.rules.ExpectedException.handleException(ExpectedException.java:217)17 at org.junit.rules.ExpectedException.access$000(ExpectedException.java:63)18 at org.junit.rules.ExpectedException$ExpectedExceptionStatement.evaluate(ExpectedException.java:153)19 at org.junit.rules.RunRules.evaluate(RunRules.java:20)20 at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)21 at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)22 at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)23 at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)24 at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)25 at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)26 at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)27 at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)28 at org.junit.runners.ParentRunner.run(ParentRunner.java:309)29 at org.junit.runner.JUnitCore.run(JUnitCore.java:160)30 at org.junit.runner.JUnitCore.run(JUnitCore.java:138)31 at org.junit.runner.JUnitCore.runMain(JUnitCore.java:117)32 at org.junit.runner.JUnitCore.main(JUnitCore.java:96)

Full Screen

Full Screen

expectMessage

Using AI Code Generation

copy

Full Screen

1import org.junit.Rule;2import org.junit.Test;3import org.junit.rules.ExpectedException;4public class ExpectedExceptionTest {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 throwsNullPointerExceptionWithMessage() {13 thrown.expect(NullPointerException.class);14 thrown.expectMessage("Hello");15 throw new NullPointerException("Hello");16 }17}

Full Screen

Full Screen

expectMessage

Using AI Code Generation

copy

Full Screen

1import org.junit.Rule;2import org.junit.Test;3import org.junit.rules.ExpectedException;4public class TestExceptionMessage {5 public ExpectedException thrown = ExpectedException.none();6 public void testExceptionMessage() throws IndexOutOfBoundsException {7 final String[] array = new String[1];8 thrown.expect(IndexOutOfBoundsException.class);9 thrown.expectMessage("Index: 1, Size: 1");10 final String element = array[1];11 }12}13 at org.junit.Assert.assertEquals(Assert.java:115)14 at org.junit.Assert.assertEquals(Assert.java:144)15 at org.junit.rules.ExpectedException.access$001(ExpectedException.java:94)16 at org.junit.rules.ExpectedException$ExpectedExceptionStatement.evaluate(ExpectedException.java:109)17 at org.junit.rules.RunRules.evaluate(RunRules.java:20)18 at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)19 at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)20 at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)21 at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)22 at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)23 at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)24 at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)25 at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)26 at org.junit.runners.ParentRunner.run(ParentRunner.java:363)27 at org.junit.runner.JUnitCore.run(JUnitCore.java:137)28 at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:117)29 at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:234)30 at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:74)

Full Screen

Full Screen

expectMessage

Using AI Code Generation

copy

Full Screen

1public void testGetMessage() {2 expectedException.expectMessage("Hello");3 expectedException.expectMessage("World");4 throw new IllegalArgumentException("Hello World");5}6public void testGetMessage() {7 MatcherAssert.assertThat("Hello World", CoreMatchers.containsString("Hello"));8 MatcherAssert.assertThat("Hello World", CoreMatchers.containsString("World"));9}10public void testGetMessage() {11 Exception exception = assertThrows(IllegalArgumentException.class, () -> {12 throw new IllegalArgumentException("Hello World");13 });14 assertEquals("Hello World", exception.getMessage());15}16public void testGetMessage() {17 Exception exception = assertThrows(IllegalArgumentException.class, () -> {18 throw new IllegalArgumentException("Hello World");19 });20 assertEquals("Hello World", exception.getMessage());21}22@Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "Hello World")23public void testGetMessage() {24 throw new IllegalArgumentException("Hello World");25}26def "test getMessage"() {27 throw new IllegalArgumentException("Hello World")28 e << thrown()29}30public void testGetMessage() {31 Exception exception = assertThrows(IllegalArgumentException.class, () -> {32 throw new IllegalArgumentException("Hello World");33 });34 assertEquals("Hello World", exception.getMessage());35}

Full Screen

Full Screen

expectMessage

Using AI Code Generation

copy

Full Screen

1 public void testExceptionMessage() {2 ExpectedException thrown = ExpectedException.none();3 thrown.expect(IllegalArgumentException.class);4 thrown.expectMessage("IllegalArgument");5 throw new IllegalArgumentException("IllegalArgument");6 }7 public void testExceptionMessageWithMatcher() {8 ExpectedException thrown = ExpectedException.none();9 thrown.expect(IllegalArgumentException.class);10 thrown.expectMessage(containsString("IllegalArgument"));11 throw new IllegalArgumentException("IllegalArgument");12 }13 public void testExceptionMessageWithMatcher2() {14 ExpectedException thrown = ExpectedException.none();15 thrown.expect(IllegalArgumentException.class);16 thrown.expectMessage(startsWith("Illegal"));17 throw new IllegalArgumentException("IllegalArgument");18 }19 public void testExceptionMessageWithMatcher3() {20 ExpectedException thrown = ExpectedException.none();21 thrown.expect(IllegalArgumentException.class);22 thrown.expectMessage(endsWith("Argument"));23 throw new IllegalArgumentException("IllegalArgument");24 }25 public void testExceptionMessageWithMatcher4() {26 ExpectedException thrown = ExpectedException.none();27 thrown.expect(IllegalArgumentException.class);28 thrown.expectMessage(both(containsString("Illegal")).and(containsString("Argument")));29 throw new IllegalArgumentException("IllegalArgument");

Full Screen

Full Screen

JUnit Tutorial:

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.

JUnit Tutorial Chapters:

Here are the detailed JUnit testing chapters to help you get started:

  • Importance of Unit testing - Learn why Unit testing is essential during the development phase to identify bugs and errors.
  • Top Java Unit testing frameworks - Here are the upcoming JUnit automation testing frameworks that you can use in 2023 to boost your unit testing.
  • What is the JUnit framework
  • Why is JUnit testing important - Learn the importance and numerous benefits of using the JUnit testing framework.
  • Features of JUnit - Learn about the numerous features of JUnit and why developers prefer it.
  • JUnit 5 vs. JUnit 4: Differences - Here is a complete comparison between JUnit 5 and JUnit 4 testing frameworks.
  • Setting up the JUnit environment - Learn how to set up your JUnit testing environment.
  • Getting started with JUnit testing - After successfully setting up your JUnit environment, this chapter will help you get started with JUnit testing in no time.
  • Parallel testing with JUnit - Parallel Testing can be used to reduce test execution time and improve test efficiency. Learn how to perform parallel testing with JUnit.
  • Annotations in JUnit - When writing automation scripts with JUnit, we can use JUnit annotations to specify the type of methods in our test code. This helps us identify those methods when we run JUnit tests using Selenium WebDriver. Learn in detail what annotations are in JUnit.
  • Assertions in JUnit - Assertions are used to validate or test that the result of an action/functionality is the same as expected. Learn in detail what assertions are and how to use them while performing JUnit testing.
  • Parameterization in JUnit - Parameterized Test enables you to run the same automated test scripts with different variables. By collecting data on each method's test parameters, you can minimize time spent on writing tests. Learn how to use parameterization in JUnit.
  • Nested Tests In JUnit 5 - A nested class is a non-static class contained within another class in a hierarchical structure. It can share the state and setup of the outer class. Learn about nested annotations in JUnit 5 with examples.
  • Best practices for JUnit testing - Learn about the best practices, such as always testing key methods and classes, integrating JUnit tests with your build, and more to get the best possible results.
  • Advanced Use Cases for JUnit testing - Take a deep dive into the advanced use cases, such as how to run JUnit tests in Jupiter, how to use JUnit 5 Mockito for Unit testing, and more for JUnit testing.

JUnit Certification:

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.

Run junit automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful