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

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

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:ExpectedExceptionCheckerTest.java Github

copy

Full Screen

...23public class ExpectedExceptionCheckerTest {24 private final BugCheckerRefactoringTestHelper testHelper =25 BugCheckerRefactoringTestHelper.newInstance(ExpectedExceptionChecker.class, getClass());26 @Test27 public void expect() {28 testHelper29 .addInputLines(30 "in/ExceptionTest.java",31 "import static com.google.common.truth.Truth.assertThat;",32 "import java.io.IOException;",33 "import java.nio.file.*;",34 "import org.junit.Test;",35 "import org.junit.Rule;",36 "import org.hamcrest.CoreMatchers;",37 "import org.junit.rules.ExpectedException;",38 "class ExceptionTest {",39 " @Rule ExpectedException thrown = ExpectedException.none();",40 " @Test",41 " public void test() throws Exception {",42 " if (true) {",43 " Path p = Paths.get(\"NOSUCH\");",44 " thrown.expect(IOException.class);",45 " thrown.expect(CoreMatchers.is(CoreMatchers.instanceOf(IOException.class)));",46 " thrown.expectCause(",47 " CoreMatchers.is(CoreMatchers.instanceOf(IOException.class)));",48 " thrown.expectMessage(\"error\");",49 " thrown.expectMessage(CoreMatchers.containsString(\"error\"));",50 " Files.readAllBytes(p);",51 " assertThat(Files.exists(p)).isFalse();",52 " }",53 " }",54 "}")55 .addOutputLines(56 "out/ExceptionTest.java",57 "import static com.google.common.truth.Truth.assertThat;",58 "import static org.hamcrest.MatcherAssert.assertThat;",59 "import static org.junit.Assert.assertThrows;",60 "",61 "import java.io.IOException;",62 "import java.nio.file.*;",63 "import org.hamcrest.CoreMatchers;",64 "import org.junit.Rule;",65 "import org.junit.Test;",66 "import org.junit.rules.ExpectedException;",67 "class ExceptionTest {",68 " @Rule ExpectedException thrown = ExpectedException.none();",69 " @Test",70 " public void test() throws Exception {",71 " if (true) {",72 " Path p = Paths.get(\"NOSUCH\");",73 " IOException thrown =",74 " assertThrows(IOException.class, () -> Files.readAllBytes(p));",75 " assertThat(thrown,",76 " CoreMatchers.is(CoreMatchers.instanceOf(IOException.class)));",77 " assertThat(thrown.getCause(),",78 " CoreMatchers.is(CoreMatchers.instanceOf(IOException.class)));",79 " assertThat(thrown).hasMessageThat().contains(\"error\");",80 " assertThat(thrown.getMessage(), CoreMatchers.containsString(\"error\"));",81 " assertThat(Files.exists(p)).isFalse();",82 " }",83 " }",84 "}")85 .doTest();86 }87 @Test88 public void noExceptionType() {89 testHelper90 .addInputLines(91 "in/ExceptionTest.java",92 "import static com.google.common.truth.Truth.assertThat;",93 "import java.io.IOException;",94 "import java.nio.file.*;",95 "import org.hamcrest.CoreMatchers;",96 "import org.junit.Rule;",97 "import org.junit.Test;",98 "import org.junit.rules.ExpectedException;",99 "class ExceptionTest {",100 " @Rule ExpectedException thrown = ExpectedException.none();",101 " @Test",102 " public void test() throws Exception {",103 " Path p = Paths.get(\"NOSUCH\");",104 " thrown.expect(CoreMatchers.is(CoreMatchers.instanceOf(IOException.class)));",105 " Files.readAllBytes(p);",106 " Files.readAllBytes(p);",107 " }",108 "}")109 .addOutputLines(110 "out/ExceptionTest.java",111 "import static com.google.common.truth.Truth.assertThat;",112 "import static org.hamcrest.MatcherAssert.assertThat;",113 "import static org.junit.Assert.assertThrows;",114 "",115 "import java.io.IOException;",116 "import java.nio.file.*;",117 "import org.hamcrest.CoreMatchers;",118 "import org.junit.Rule;",119 "import org.junit.Test;",120 "import org.junit.rules.ExpectedException;",121 "class ExceptionTest {",122 " @Rule ExpectedException thrown = ExpectedException.none();",123 " @Test",124 " public void test() throws Exception {",125 " Path p = Paths.get(\"NOSUCH\");",126 " Throwable thrown = assertThrows(Throwable.class, () -> {",127 " Files.readAllBytes(p);",128 " Files.readAllBytes(p);",129 " });",130 " assertThat(thrown, CoreMatchers.is(CoreMatchers.instanceOf(IOException.class)));",131 " }",132 "}")133 .doTest();134 }135 @Test136 public void noExpectations() {137 testHelper138 .addInputLines(139 "in/ExceptionTest.java",140 "import static com.google.common.truth.Truth.assertThat;",141 "import java.io.IOException;",142 "import java.nio.file.*;",143 "import org.hamcrest.CoreMatchers;",144 "import org.junit.Rule;",145 "import org.junit.Test;",146 "import org.junit.rules.ExpectedException;",147 "class ExceptionTest {",148 " @Rule ExpectedException thrown = ExpectedException.none();",149 " @Test",150 " public void test() throws Exception {",151 " Path p = Paths.get(\"NOSUCH\");",152 " thrown.expect(IOException.class);",153 " Files.readAllBytes(p);",154 " assertThat(Files.exists(p)).isFalse();",155 " }",156 "}")157 .addOutputLines(158 "out/ExceptionTest.java",159 "import static com.google.common.truth.Truth.assertThat;",160 "import static org.junit.Assert.assertThrows;",161 "import java.io.IOException;",162 "import java.nio.file.*;",163 "import org.hamcrest.CoreMatchers;",164 "import org.junit.Rule;",165 "import org.junit.Test;",166 "import org.junit.rules.ExpectedException;",167 "class ExceptionTest {",168 " @Rule ExpectedException thrown = ExpectedException.none();",169 " @Test",170 " public void test() throws Exception {",171 " Path p = Paths.get(\"NOSUCH\");",172 " assertThrows(IOException.class, () -> Files.readAllBytes(p));",173 " assertThat(Files.exists(p)).isFalse();",174 " }",175 "}")176 .doTest();177 }178 @Test179 public void nonExpressionStatement() {180 testHelper181 .addInputLines(182 "in/ExceptionTest.java",183 "import static com.google.common.truth.Truth.assertThat;",184 "import java.io.IOException;",185 "import java.nio.file.*;",186 "import org.junit.Rule;",187 "import org.junit.Test;",188 "import org.junit.rules.ExpectedException;",189 "class ExceptionTest {",190 " @Rule ExpectedException thrown = ExpectedException.none();",191 " @Test",192 " public void test() throws Exception {",193 " Path p = Paths.get(\"NOSUCH\");",194 " thrown.expect(IOException.class);",195 " Files.readAllBytes(p);",196 " if (true) Files.readAllBytes(p);",197 " }",198 "}")199 .addOutputLines(200 "out/ExceptionTest.java",201 "import static com.google.common.truth.Truth.assertThat;",202 "import static org.junit.Assert.assertThrows;",203 "",204 "import java.io.IOException;",205 "import java.nio.file.*;",206 "import org.junit.Rule;",207 "import org.junit.Test;",208 "import org.junit.rules.ExpectedException;",209 "class ExceptionTest {",210 " @Rule ExpectedException thrown = ExpectedException.none();",211 " @Test",212 " public void test() throws Exception {",213 " Path p = Paths.get(\"NOSUCH\");",214 " assertThrows(IOException.class, () -> {",215 " Files.readAllBytes(p);",216 " if (true) Files.readAllBytes(p);",217 " });",218 " }",219 "}")220 .doTest();221 }222 // https://github.com/hamcrest/JavaHamcrest/issues/27223 @Test224 public void isA_hasCauseThat() {225 testHelper226 .addInputLines(227 "in/ExceptionTest.java",228 "import static com.google.common.truth.Truth.assertThat;",229 "import java.io.IOException;",230 "import java.nio.file.*;",231 "import org.junit.Test;",232 "import org.junit.Rule;",233 "import org.hamcrest.CoreMatchers;",234 "import org.junit.rules.ExpectedException;",235 "class ExceptionTest {",236 " @Rule ExpectedException thrown = ExpectedException.none();",237 " @Test",238 " public void test() throws Exception {",239 " Path p = Paths.get(\"NOSUCH\");",240 " thrown.expect(IOException.class);",241 " thrown.expectCause(CoreMatchers.isA(IOException.class));",242 " thrown.expectCause(org.hamcrest.core.Is.isA(IOException.class));",243 " Files.readAllBytes(p);",244 " assertThat(Files.exists(p)).isFalse();",245 " }",246 "}")247 .addOutputLines(248 "out/ExceptionTest.java",249 "import static com.google.common.truth.Truth.assertThat;",250 "import static org.junit.Assert.assertThrows;",251 "",252 "import java.io.IOException;",253 "import java.nio.file.*;",254 "import org.hamcrest.CoreMatchers;",255 "import org.junit.Rule;",256 "import org.junit.Test;",257 "import org.junit.rules.ExpectedException;",258 "class ExceptionTest {",259 " @Rule ExpectedException thrown = ExpectedException.none();",260 " @Test",261 " public void test() throws Exception {",262 " Path p = Paths.get(\"NOSUCH\");",263 " IOException thrown =",264 " assertThrows(IOException.class, () -> Files.readAllBytes(p));",265 " assertThat(thrown).hasCauseThat().isInstanceOf(IOException.class);",266 " assertThat(thrown).hasCauseThat().isInstanceOf(IOException.class);",267 " assertThat(Files.exists(p)).isFalse();",268 " }",269 "}")270 .doTest();271 }272 @Test273 public void typedMatcher() {274 testHelper275 .addInputLines(276 "in/ExceptionTest.java",277 "import static com.google.common.truth.Truth.assertThat;",278 "import java.io.IOException;",279 "import java.nio.file.*;",280 "import org.junit.Test;",281 "import org.junit.Rule;",282 "import org.hamcrest.Matcher;",283 "import org.junit.rules.ExpectedException;",284 "class ExceptionTest {",285 " @Rule ExpectedException thrown = ExpectedException.none();",286 " Matcher<IOException> matcher;",287 " @Test",288 " public void test() throws Exception {",289 " Path p = Paths.get(\"NOSUCH\");",290 " thrown.expect(matcher);",291 " Files.readAllBytes(p);",292 " assertThat(Files.exists(p)).isFalse();",293 " }",294 "}")295 .addOutputLines(296 "out/ExceptionTest.java",297 "import static com.google.common.truth.Truth.assertThat;",298 "import static org.hamcrest.MatcherAssert.assertThat;",299 "import static org.junit.Assert.assertThrows;",300 "",301 "import java.io.IOException;",302 "import java.nio.file.*;",303 "import org.hamcrest.Matcher;",304 "import org.junit.Rule;",305 "import org.junit.Test;",306 "import org.junit.rules.ExpectedException;",307 "class ExceptionTest {",308 " @Rule ExpectedException thrown = ExpectedException.none();",309 " Matcher<IOException> matcher;",310 " @Test",311 " public void test() throws Exception {",312 " Path p = Paths.get(\"NOSUCH\");",313 " IOException thrown =",314 " assertThrows(IOException.class, () -> Files.readAllBytes(p));",315 " assertThat(thrown, matcher);",316 " assertThat(Files.exists(p)).isFalse();",317 " }",318 "}")319 .doTest();320 }321 @Test322 public void nothingButAsserts() {323 testHelper324 .addInputLines(325 "in/ExceptionTest.java",326 "import static com.google.common.truth.Truth.assertThat;",327 "import org.junit.Rule;",328 "import org.junit.Test;",329 "import org.junit.rules.ExpectedException;",330 "class ExceptionTest {",331 " @Rule ExpectedException thrown = ExpectedException.none();",332 " @Test",333 " public void test() throws Exception {",334 " thrown.expect(RuntimeException.class);",335 " assertThat(false).isFalse();",336 " assertThat(true).isTrue();",337 " }",338 "}")339 .addOutputLines(340 "out/ExceptionTest.java",341 "import static com.google.common.truth.Truth.assertThat;",342 "import org.junit.Rule;",343 "import org.junit.Test;",344 "import org.junit.rules.ExpectedException;",345 "class ExceptionTest {",346 " @Rule ExpectedException thrown = ExpectedException.none();",347 " @Test",348 " public void test() throws Exception {",349 " assertThat(false).isFalse();",350 " assertThat(true).isTrue();",351 " }",352 "}")353 .doTest();354 }355 @Test356 public void removeExplicitFail() {357 testHelper358 .addInputLines(359 "in/ExceptionTest.java",360 "import static com.google.common.truth.Truth.assertThat;",361 "import static org.junit.Assert.fail;",362 "import java.io.IOException;",363 "import java.nio.file.*;",364 "import org.junit.Test;",365 "import org.junit.Rule;",366 "import org.junit.rules.ExpectedException;",367 "class ExceptionTest {",368 " @Rule ExpectedException thrown = ExpectedException.none();",369 " @Test",370 " public void testThrow() throws Exception {",371 " thrown.expect(IOException.class);",372 " throw new IOException();",373 " }",374 " @Test",375 " public void one() throws Exception {",376 " Path p = Paths.get(\"NOSUCH\");",377 " thrown.expect(IOException.class);",378 " Files.readAllBytes(p);",379 " assertThat(Files.exists(p)).isFalse();",380 " fail();",381 " }",382 " @Test",383 " public void two() throws Exception {",384 " Path p = Paths.get(\"NOSUCH\");",385 " thrown.expect(IOException.class);",386 " Files.readAllBytes(p);",387 " assertThat(Files.exists(p)).isFalse();",388 " throw new AssertionError();",389 " }",390 "}")391 .addOutputLines(392 "out/ExceptionTest.java",393 "import static com.google.common.truth.Truth.assertThat;",394 "import static org.junit.Assert.assertThrows;",395 "import static org.junit.Assert.fail;",396 "",397 "import java.io.IOException;",398 "import java.nio.file.*;",399 "import org.junit.Rule;",400 "import org.junit.Test;",401 "import org.junit.rules.ExpectedException;",402 "class ExceptionTest {",403 " @Rule ExpectedException thrown = ExpectedException.none();",404 " @Test",405 " public void testThrow() throws Exception {",406 " }",407 " @Test",408 " public void one() throws Exception {",409 " Path p = Paths.get(\"NOSUCH\");",410 " assertThrows(IOException.class, () -> Files.readAllBytes(p));",411 " assertThat(Files.exists(p)).isFalse();",412 " }",413 " @Test",414 " public void two() throws Exception {",415 " Path p = Paths.get(\"NOSUCH\");",416 " assertThrows(IOException.class, () -> Files.readAllBytes(p));",417 " assertThat(Files.exists(p)).isFalse();",418 " }",419 "}")420 .doTest();421 }422 // https://github.com/google/error-prone/issues/1072423 @Test424 public void i1072() {425 testHelper426 .addInputLines(427 "in/ExceptionTest.java",428 "import org.junit.Rule;",429 "import org.junit.Test;",430 "import org.junit.rules.ExpectedException;",431 "class ExceptionTest {",432 " @Rule ExpectedException thrown = ExpectedException.none();",433 " @Test",434 " public void testThrow(Class<? extends Throwable> clazz) throws Exception {",435 " thrown.expect(clazz);",436 " clazz.toString();",437 " }",438 "}")439 .addOutputLines(440 "in/ExceptionTest.java",441 "import static org.junit.Assert.assertThrows;",442 "import org.junit.Rule;",443 "import org.junit.Test;",444 "import org.junit.rules.ExpectedException;",445 "class ExceptionTest {",446 " @Rule ExpectedException thrown = ExpectedException.none();",447 " @Test",448 " public void testThrow(Class<? extends Throwable> clazz) throws Exception {",449 " assertThrows(Throwable.class, () -> clazz.toString());",...

Full Screen

Full Screen

Source:ExpectedExceptionTest.java Github

copy

Full Screen

...38 ThrowExceptionWithWrongType.class,39 hasSingleFailureWithMessage(startsWith("\nExpected: an instance of java.lang.NullPointerException"))},40 {41 HasWrongMessage.class,42 hasSingleFailureWithMessage(startsWith("\nExpected: exception with message a string containing \"expectedMessage\"\n"43 + " but: message was \"actualMessage\""))},44 {45 ThrowNoExceptionButExpectExceptionWithType.class,46 hasSingleFailureWithMessage("Expected test to throw an instance of java.lang.NullPointerException")},47 {WronglyExpectsExceptionMessage.class, hasSingleFailure()},48 {ExpectsSubstring.class, everyTestRunSuccessful()},49 {50 ExpectsSubstringNullMessage.class,51 hasSingleFailureWithMessage(startsWith("\nExpected: exception with message a string containing \"anything!\""))},52 {ExpectsMessageMatcher.class, everyTestRunSuccessful()},53 {54 ExpectedMessageMatcherFails.class,55 hasSingleFailureWithMessage(startsWith("\nExpected: exception with message \"Wrong start\""))},56 {ExpectsMatcher.class, everyTestRunSuccessful()},57 {ExpectAssertionErrorWhichIsNotThrown.class, hasSingleFailure()},58 {FailedAssumptionAndExpectException.class,59 hasSingleAssumptionFailure()},60 {FailBeforeExpectingException.class,61 hasSingleFailureWithMessage(ARBITRARY_MESSAGE)},62 {63 ExpectsMultipleMatchers.class,64 hasSingleFailureWithMessage(startsWith("\nExpected: (an instance of java.lang.IllegalArgumentException and exception with message a string containing \"Ack!\")"))},65 {ThrowExceptionWithMatchingCause.class, everyTestRunSuccessful()},66 {ThrowExpectedNullCause.class, everyTestRunSuccessful()},67 {68 ThrowUnexpectedCause.class,69 hasSingleFailureWithMessage(CoreMatchers.<String>allOf(70 startsWith("\nExpected: ("),71 containsString("exception with cause is <java.lang.NullPointerException: expected cause>"),72 containsString("cause was <java.lang.NullPointerException: an unexpected cause>"),73 containsString("Stacktrace was: java.lang.IllegalArgumentException: Ack!"),74 containsString("Caused by: java.lang.NullPointerException: an unexpected cause")))},75 {76 UseNoCustomMessage.class,77 hasSingleFailureWithMessage("Expected test to throw an instance of java.lang.IllegalArgumentException") },78 {79 UseCustomMessageWithoutPlaceHolder.class,80 hasSingleFailureWithMessage(ARBITRARY_MESSAGE) },81 {82 UseCustomMessageWithPlaceHolder.class,83 hasSingleFailureWithMessage(ARBITRARY_MESSAGE84 + " - an instance of java.lang.IllegalArgumentException") },85 {86 ErrorCollectorShouldFailAlthoughExpectedExceptionDoesNot.class,87 hasSingleFailureWithMessage(ARBITRARY_MESSAGE) }88 });89 }90 private final Class<?> classUnderTest;91 private final Matcher<EventCollector> matcher;92 public ExpectedExceptionTest(Class<?> classUnderTest,93 Matcher<EventCollector> matcher) {94 this.classUnderTest = classUnderTest;95 this.matcher = matcher;96 }97 @Test98 public void runTestAndVerifyResult() {99 EventCollector collector = new EventCollector();100 JUnitCore core = new JUnitCore();101 core.addListener(collector);102 core.run(classUnderTest);103 assertThat(collector, matcher);104 }105 public static class EmptyTestExpectingNoException {106 @Rule107 public ExpectedException thrown = none();108 @Test109 public void throwsNothing() {110 }111 }112 public static class ThrowExceptionWithExpectedType {113 @Rule114 public ExpectedException thrown = none();115 @Test116 public void throwsNullPointerException() {117 thrown.expect(NullPointerException.class);118 throw new NullPointerException();119 }120 }121 public static class ThrowExceptionWithExpectedPartOfMessage {122 @Rule123 public ExpectedException thrown = none();124 @Test125 public void throwsNullPointerExceptionWithMessage() {126 thrown.expect(NullPointerException.class);127 thrown.expectMessage(ARBITRARY_MESSAGE);128 throw new NullPointerException(ARBITRARY_MESSAGE + "something else");129 }130 }131 public static class ThrowExceptionWithWrongType {132 @Rule133 public ExpectedException thrown = none();134 @Test135 public void throwsNullPointerException() {136 thrown.expect(NullPointerException.class);137 throw new IllegalArgumentException();138 }139 }140 public static class HasWrongMessage {141 @Rule142 public ExpectedException thrown = none();143 @Test144 public void throwsNullPointerException() {145 thrown.expectMessage("expectedMessage");146 throw new IllegalArgumentException("actualMessage");147 }148 }149 public static class ThrowNoExceptionButExpectExceptionWithType {150 @Rule151 public ExpectedException thrown = none();152 @Test153 public void doesntThrowNullPointerException() {154 thrown.expect(NullPointerException.class);155 }156 }157 public static class WronglyExpectsExceptionMessage {158 @Rule159 public ExpectedException thrown = none();160 @Test161 public void doesntThrowAnything() {162 thrown.expectMessage("anything!");163 }164 }165 public static class ExpectsSubstring {166 @Rule167 public ExpectedException thrown = none();168 @Test169 public void throwsMore() {170 thrown.expectMessage("anything!");171 throw new NullPointerException(172 "This could throw anything! (as long as it has the right substring)");173 }174 }175 public static class ExpectsSubstringNullMessage {176 @Rule177 public ExpectedException thrown = none();178 @Test179 public void throwsMore() {180 thrown.expectMessage("anything!");181 throw new NullPointerException();182 }183 }184 public static class ExpectsMessageMatcher {185 @Rule186 public ExpectedException thrown = none();187 @Test188 public void throwsMore() {189 thrown.expectMessage(startsWith(ARBITRARY_MESSAGE));190 throw new NullPointerException(ARBITRARY_MESSAGE + "!");191 }192 }193 public static class ExpectedMessageMatcherFails {194 @Rule195 public ExpectedException thrown = none();196 @Test197 public void throwsMore() {198 thrown.expectMessage(equalTo("Wrong start"));199 throw new NullPointerException("Back!");200 }201 }202 public static class ExpectsMatcher {203 @Rule204 public ExpectedException thrown = none();205 @Test206 public void throwsMore() {207 thrown.expect(any(Exception.class));208 throw new NullPointerException("Ack!");209 }210 }211 public static class ExpectsMultipleMatchers {212 @Rule213 public ExpectedException thrown = none();214 @Test215 public void throwsMore() {216 thrown.expect(IllegalArgumentException.class);217 thrown.expectMessage("Ack!");218 throw new NullPointerException("Ack!");219 }220 }221 //https://github.com/junit-team/junit4/pull/583222 public static class ExpectAssertionErrorWhichIsNotThrown {223 @Rule224 public ExpectedException thrown = none();225 @Test226 public void fails() {227 thrown.expect(AssertionError.class);228 }229 }230 public static class FailBeforeExpectingException {231 @Rule232 public ExpectedException thrown = none();233 @Test234 public void fails() {235 fail(ARBITRARY_MESSAGE);236 thrown.expect(IllegalArgumentException.class);237 }238 }239 public static class FailedAssumptionAndExpectException {240 @Rule241 public ExpectedException thrown = none();242 @Test243 public void failedAssumption() {244 assumeTrue(false);245 thrown.expect(NullPointerException.class);246 }247 }248 public static class ThrowExceptionWithMatchingCause {249 @Rule250 public ExpectedException thrown = none();251 @Test252 public void throwExceptionWithMatchingCause() {253 NullPointerException expectedCause = new NullPointerException("expected cause");254 thrown.expect(IllegalArgumentException.class);255 thrown.expectMessage("Ack!");256 thrown.expectCause(is(expectedCause));257 throw new IllegalArgumentException("Ack!", expectedCause);258 }259 }260 public static class ThrowExpectedNullCause {261 @Rule262 public ExpectedException thrown = none();263 @Test264 public void throwExpectedNullCause() {265 thrown.expect(IllegalArgumentException.class);266 thrown.expectMessage("Ack!");267 thrown.expectCause(nullValue(Throwable.class));268 throw new IllegalArgumentException("Ack!");269 }270 }271 public static class ThrowUnexpectedCause {272 @Rule273 public ExpectedException thrown = ExpectedException.none();274 @Test275 public void throwWithCause() {276 thrown.expect(IllegalArgumentException.class);277 thrown.expectMessage("Ack!");278 thrown.expectCause(is(new NullPointerException("expected cause")));279 throw new IllegalArgumentException("Ack!", new NullPointerException("an unexpected cause"));280 }281 }282 283 public static class UseNoCustomMessage {284 @Rule285 public ExpectedException thrown= ExpectedException.none();286 @Test287 public void noThrow() {288 thrown.expect(IllegalArgumentException.class);289 }290 }291 public static class UseCustomMessageWithPlaceHolder {292 @Rule293 public ExpectedException thrown = ExpectedException.none();294 @Test295 public void noThrow() {296 thrown.expect(IllegalArgumentException.class);297 thrown.reportMissingExceptionWithMessage(ARBITRARY_MESSAGE298 + " - %s");299 }300 }301 public static class UseCustomMessageWithoutPlaceHolder {302 @Rule303 public ExpectedException thrown= ExpectedException.none();304 @Test305 public void noThrow() {306 thrown.expect(IllegalArgumentException.class);307 thrown.reportMissingExceptionWithMessage(ARBITRARY_MESSAGE);308 }309 }310 public static class ErrorCollectorShouldFailAlthoughExpectedExceptionDoesNot {311 @Rule312 public ErrorCollector collector = new ErrorCollector();313 @Rule(order = Integer.MAX_VALUE)314 public ExpectedException thrown = ExpectedException.none();315 @Test316 public void test() {317 collector.addError(new AssertionError(ARBITRARY_MESSAGE));318 thrown.expect(Exception.class);319 throw new RuntimeException();320 }321 }322}...

Full Screen

Full Screen

Source:JunitRuleTest.java Github

copy

Full Screen

...43 @Rule44 public MethodLoggingRule methodLogger = new MethodLoggingRule();45 // ExpectedException可以匹配异常类型和异常message46 @Rule47 public ExpectedException expectedException = ExpectedException.none();48 @Rule49 public RuleChain ruleChain = RuleChain.outerRule(new LoggingRule(3)).around(new LoggingRule(2)).around(new LoggingRule(1));50 @Test51 public void testTemporaryFolder() throws Exception {52 File file = temporaryFolder.newFile();53 log.info("file: {}", file.getAbsolutePath());54 FileUtils.writeStringToFile(file, "abc", "utf-8", true);55 log.info("read data: {}", FileUtils.readFileToString(file, "utf-8"));56 TimeUnit.SECONDS.sleep(10);57 }58 @Test59 public void testTimeout() throws InterruptedException {60 TimeUnit.SECONDS.sleep(20);61 }62 @Test63 public void testNotTimeout() throws InterruptedException {64 TimeUnit.SECONDS.sleep(1);65 }66 @Test67 public void testMethodLogRule() throws InterruptedException {68 TimeUnit.MILLISECONDS.sleep(1234);69 }70 @Test71 public void testExpectException1() {72 expectedException.expect(NumberFormatException.class);73 expectedException.expectMessage("For input string: \"a\"");74 Integer.parseInt("a");75 }76 @Test(expected = ArithmeticException.class)77 public void testExpectException2() {78 int n = 1 / 0;79 }80 @Test81 public void testRuleChain() {82 }83 @Slf4j84 private static class MethodLoggingRule implements MethodRule {85 @Override86 public Statement apply(Statement base, FrameworkMethod method, Object target) {87 String flag = target.getClass().getSimpleName() + "." + method.getName();88 return new Statement() {89 @Override90 public void evaluate() throws Throwable {...

Full Screen

Full Screen

Source:ExpectedException.java Github

copy

Full Screen

...25import org.junit.runners.model.Statement;26import static org.hamcrest.CoreMatchers.equalTo;27/**28 * A custom variant of {@link org.junit.rules.ExpectedException} that verifies that the whole exception message29 * is identical to the expected message instead of just if the message contains the expected message.30 *31 * @author Christian Ihle32 */33public class ExpectedException implements TestRule {34 private final org.junit.rules.ExpectedException expectedException = org.junit.rules.ExpectedException.none();35 public static ExpectedException none() {36 return new ExpectedException();37 }38 @Override39 public Statement apply(final Statement base, final Description description) {40 return expectedException.apply(base, description);41 }42 /**43 * Which exception to expect.44 */45 public void expect(final Class<? extends Throwable> expectedExceptionClass) {46 expectedException.expect(expectedExceptionClass);47 }48 /**49 * The exact exception message to expect.50 */51 public void expectMessage(@NonNls final String expectedExceptionMessage) {52 expectedException.expectMessage(equalTo(expectedExceptionMessage));53 }54 /**55 * A part of the exception message to expect.56 */57 public void expectMessageContaining(@NonNls final String substring) {58 expectedException.expectMessage(substring);59 }60}...

Full Screen

Full Screen

Source:RuleTester.java Github

copy

Full Screen

...17 * @date 2022/2/2018 */19public class RuleTester {20 @Rule21 public ExpectedException expectedException = ExpectedException.none();22 @Rule23 public TemporaryFolder folder = new TemporaryFolder();24 private Calculator calculator = new Calculator();25 private static File createdFolder;26 private static File createdFile;27 @Test28 public void expectIllegalArgumentException() {29 expectedException.expect(IllegalArgumentException.class);30 expectedException.expectMessage("Cannot extract the square root of a negative value");31 calculator.sqrt(-1);32 }33 @Test34 public void expectArithmeticException() {35 expectedException.expect(ArithmeticException.class);36 expectedException.expectMessage("Cannot divide by zero");37 calculator.divide(1, 0);38 }39 @Test40 public void testTemporaryFolder() throws IOException {41 createdFolder = folder.newFolder("createdFolder");42 createdFile = folder.newFile("createdFile.txt");43 assertTrue(createdFolder.exists());44 assertTrue(createdFile.exists());45 }46 @AfterClass47 public static void cleanUpAfterAllTestsRan() {48 assertFalse(createdFolder.exists());49 assertFalse(createdFile.exists());50 }...

Full Screen

Full Screen

Source:JUnit4BuiltInTestRulesTest.java Github

copy

Full Screen

...14import org.junit.rules.TemporaryFolder;1516public class JUnit4BuiltInTestRulesTest {17 /*18 * you can use this template to create expected exceptions rules fast:19 * ${staticImp:importStatic(org.junit.rules.ExpectedException.none)}20 * ${imp:import(org.junit.Rule,org.junit.rules.ExpectedException)}@Rule21 * public ExpectedException exception = none();22 */2324 @Rule25 public ExpectedException exception = none();2627 @Rule28 public TemporaryFolder folder = new TemporaryFolder(); // can be called with29 // parent folder3031 @Test32 public void comparingToExpectedInTestAnnotationWeCanValidateCauseAndMessageToo() throws Exception {33 exception.expect(RuntimeException.class);34 exception.expectCause(isA(IOException.class));35 exception.expectMessage("substring");3637 throw new IllegalArgumentException("Message containing substring", new IOException("the cause"));38 }3940 @Test41 public void youCanUseTemporaryFoldersThatAreRemovedAfterTheTests() throws Exception {42 File root = folder.getRoot();43 assertThat(root.exists(), is(true));4445 File anyTemporaryFile = folder.newFile();46 assertThat(anyTemporaryFile.exists(), is(true));47 }48}

Full Screen

Full Screen

Source:ExpectedLogMessagesRuleTest.java Github

copy

Full Screen

...9/** Tests for {@link ExpectedLogMessagesRule}. */10@RunWith(AndroidJUnit4.class)11public final class ExpectedLogMessagesRuleTest {12 private ExpectedLogMessagesRule rule = new ExpectedLogMessagesRule();13 private ExpectedException expectedException = ExpectedException.none();14 @Rule public RuleChain chain = RuleChain.outerRule(expectedException).around(rule);15 @Test16 public void testAndroidExpectedLogMessagesFailsWithMessage() throws Exception {17 expectedException.expect(AssertionError.class);18 Log.e("Mytag", "What's up");19 }20 @Test21 public void testAndroidExpectedLogMessagesDoesNotFailWithExpected() throws Exception {22 rule.expectErrorsForTag("Mytag");23 Log.e("Mytag", "What's up");24 }25 @Test26 public void testNoExpectedMessageFailsTest() throws Exception {27 expectedException.expect(AssertionError.class);28 rule.expectLogMessage(Log.ERROR, "Mytag", "What's up");29 }30 @Test31 public void testNoExpectedTagFailsTest() throws Exception {32 expectedException.expect(AssertionError.class);33 rule.expectErrorsForTag("Mytag");34 }35}...

Full Screen

Full Screen

Source:RepeatUntilExpectedExceptionRule.java Github

copy

Full Screen

...5import org.junit.runner.Description;6import org.junit.runners.model.Statement;7import static com.bluecatcode.junit.rules.RepeatRule.RepeatStatement.createFromAnnotationWith;8public class RepeatUntilExpectedExceptionRule implements TestRule {9 private ExpectedException expectedException = ExpectedException.none();10 @Override11 public Statement apply(Statement statement, Description description) {12 Repeat repeat = description.getAnnotation(Repeat.class);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

expect

Using AI Code Generation

copy

Full Screen

1import org.junit.Rule;2import org.junit.Test;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 throwsNullPointerExceptionWithMessage() {13 thrown.expect(NullPointerException.class);14 thrown.expectMessage("Hello");15 throw new NullPointerException("Hello");16 }17 public void throwsNullPointerExceptionWithMessageContaining() {18 thrown.expect(NullPointerException.class);19 thrown.expectMessage("Hello");20 throw new NullPointerException("Hello World");21 }22}23 at org.junit.Assert.assertEquals(Assert.java:115)24 at org.junit.Assert.assertEquals(Assert.java:144)25 at org.junit.rules.ExpectedException.handleException(ExpectedException.java:239)26 at org.junit.rules.ExpectedException.access$000(ExpectedException.java:67)27 at org.junit.rules.ExpectedException$ExpectedExceptionStatement.evaluate(ExpectedException.java:231)28 at org.junit.runners.model.Statement.evaluate(Statement.java:87)29 at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)30 at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)31 at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)32 at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)33 at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)34 at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)35 at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)36 at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)37 at org.junit.runners.ParentRunner.run(ParentRunner.java:309)38 at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)39 at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)40 at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)

Full Screen

Full Screen

expect

Using AI Code Generation

copy

Full Screen

1import org.junit.Rule;2import org.junit.Test;3import org.junit.rules.ExpectedException;4public class TestException {5 public ExpectedException thrown = ExpectedException.none();6 public void testException() {7 thrown.expect(ArithmeticException.class);8 thrown.expectMessage("/ by zero");9 int i = 1/0;10 }11}12 at org.junit.rules.ExpectedException$ExpectedExceptionStatement.evaluate(ExpectedException.java:239)13 at org.junit.rules.RunRules.evaluate(RunRules.java:20)14 at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)15 at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)16 at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)17 at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)18 at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)19 at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)20 at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)21 at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)22 at org.junit.runners.ParentRunner.run(ParentRunner.java:363)23 at org.junit.runner.JUnitCore.run(JUnitCore.java:137)24 at org.junit.runner.JUnitCore.run(JUnitCore.java:115)25 at org.junit.vintage.engine.execution.RunnerExecutor.execute(RunnerExecutor.java:43)26 at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:183)27 at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:195)28 at java.base/java.util.Iterator.forEachRemaining(Iterator.java:133)29 at java.base/java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)30 at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)31 at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)32 at java.base/java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:150)33 at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:173)34 at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)

Full Screen

Full Screen

expect

Using AI Code Generation

copy

Full Screen

1 public ExpectedException thrown = ExpectedException.none();2 public void testExceptionMessage() {3 thrown.expect(IllegalArgumentException.class);4 thrown.expectMessage("Illegal argument");5 throw new IllegalArgumentException("Illegal argument");6 }

Full Screen

Full Screen

expect

Using AI Code Generation

copy

Full Screen

1import org.junit.Rule;2import org.junit.Test;3import org.junit.rules.ExpectedException;4public class TestException {5 public ExpectedException thrown = ExpectedException.none();6 public void throwsNullPointerException() {7 thrown.expect(NullPointerException.class);8 throw new NullPointerException();9 }10}11BUILD SUCCESSFUL (total time: 0 seconds)

Full Screen

Full Screen

expect

Using AI Code Generation

copy

Full Screen

1public ExpectedException thrown = ExpectedException.none();2public void testExceptionMessage() {3 thrown.expect(IllegalArgumentException.class);4 thrown.expectMessage("exception message");5 throw new IllegalArgumentException("exception message");6}7public void testExceptionMessage() {8 Throwable exception = assertThrows(IllegalArgumentException.class, () -> {9 throw new IllegalArgumentException("exception message");10 });11 assertEquals("exception message", exception.getMessage());12}13public void testExceptionMessage() {14 IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> {15 throw new IllegalArgumentException("exception message");16 });17 assertEquals("exception message", exception.getMessage());18}19public void testExceptionMessage() {20 IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> {21 throw new IllegalArgumentException("exception message");22 });23 assertEquals("exception message", exception.getMessage());24}25public void testExceptionMessage() {26 IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> {27 throw new IllegalArgumentException("exception message");28 });29 assertEquals("exception message", exception.getMessage());30}31public void testExceptionMessage() {32 IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> {33 throw new IllegalArgumentException("exception message");34 });35 assertEquals("exception message", exception.getMessage());36}37public void testExceptionMessage() {38 IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> {39 throw new IllegalArgumentException("exception message");40 });41 assertEquals("exception message", exception.getMessage());42}43public void testExceptionMessage() {44 IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> {45 throw new IllegalArgumentException("exception message");46 });47 assertEquals("exception message", exception.getMessage());48}49public void testExceptionMessage() {50 IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> {51 throw new IllegalArgumentException("exception message");52 });53 assertEquals("exception message", exception

Full Screen

Full Screen

expect

Using AI Code Generation

copy

Full Screen

1 public void testExceptionMessage() {2 expectedEx.expect(IllegalArgumentException.class);3 expectedEx.expectMessage("Invalid input");4 throw new IllegalArgumentException("Invalid input");5 }6 public void testExceptionMessage() {7 IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> {8 throw new IllegalArgumentException("Invalid input");9 });10 assertEquals("Invalid input", exception.getMessage());11 }12 public void testExceptionMessage() {13 IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> {14 throw new IllegalArgumentException("Invalid input");15 });16 assertEquals("Invalid input", exception.getMessage());17 }18 public void testExceptionMessage() {19 IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> {20 throw new IllegalArgumentException("Invalid input");21 });22 assertEquals("Invalid input", exception.getMessage());23 }24 public void testExceptionMessage() {25 IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> {26 throw new IllegalArgumentException("Invalid input");27 });28 assertEquals("Invalid input", exception.getMessage());29 }30 public void testExceptionMessage() {31 IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> {32 throw new IllegalArgumentException("Invalid input");33 });34 assertEquals("Invalid input", exception.getMessage());35 }36 public void testExceptionMessage() {37 IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> {38 throw new IllegalArgumentException("Invalid input");39 });40 assertEquals("Invalid input", exception.getMessage());41 }42 public void testExceptionMessage() {43 IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> {44 throw new IllegalArgumentException("Invalid input");45 });46 assertEquals("Invalid input", exception.getMessage());47 }48 public void testExceptionMessage() {

Full Screen

Full Screen

expect

Using AI Code Generation

copy

Full Screen

1import org.junit.rules.ExpectedException;2import org.junit.Rule;3import org.junit.Test;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}13The following test method shows how to use expectMessage() method to specify the expected exception message:14public void throwsNullPointerExceptionWithMessage() {15 thrown.expect(NullPointerException.class);16 thrown.expectMessage("Hello");17 throw new NullPointerException("Hello");18}19The following test method shows how to use expectCause() method to specify the expected cause of the exception:20public void throwsNullPointerExceptionWithCause() {21 NullPointerException cause = new NullPointerException();22 thrown.expect(IllegalArgumentException.class);23 thrown.expectCause(is(cause));24 throw new IllegalArgumentException(cause);25}26The following test method shows how to use expectCause() method to specify the expected cause of the exception:27public void throwsNullPointerExceptionWithCause() {28 NullPointerException cause = new NullPointerException();29 thrown.expect(IllegalArgumentException.class);30 thrown.expectCause(is(cause));31 throw new IllegalArgumentException(cause);32}33The following test method shows how to use expectCause() method to specify the expected cause of the exception:34public void throwsNullPointerExceptionWithCause() {35 NullPointerException cause = new NullPointerException();

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