How to use assertThrows method of org.junit.Assert class

Best junit code snippet using org.junit.Assert.assertThrows

Source:DiscoverySelectorsTests.java Github

copy

Full Screen

...11import static java.lang.String.join;12import static java.util.Collections.singleton;13import static org.assertj.core.api.Assertions.assertThat;14import static org.junit.jupiter.api.Assertions.assertEquals;15import static org.junit.jupiter.api.Assertions.assertThrows;16import static org.junit.jupiter.params.provider.Arguments.arguments;17import static org.junit.platform.engine.discovery.DiscoverySelectors.selectClass;18import static org.junit.platform.engine.discovery.DiscoverySelectors.selectClasspathResource;19import static org.junit.platform.engine.discovery.DiscoverySelectors.selectClasspathRoots;20import static org.junit.platform.engine.discovery.DiscoverySelectors.selectDirectory;21import static org.junit.platform.engine.discovery.DiscoverySelectors.selectFile;22import static org.junit.platform.engine.discovery.DiscoverySelectors.selectMethod;23import static org.junit.platform.engine.discovery.DiscoverySelectors.selectModule;24import static org.junit.platform.engine.discovery.DiscoverySelectors.selectModules;25import static org.junit.platform.engine.discovery.DiscoverySelectors.selectPackage;26import static org.junit.platform.engine.discovery.DiscoverySelectors.selectUri;27import java.io.File;28import java.lang.reflect.Method;29import java.net.URI;30import java.nio.file.Path;31import java.nio.file.Paths;32import java.util.Arrays;33import java.util.HashSet;34import java.util.List;35import java.util.stream.Collectors;36import java.util.stream.Stream;37import org.junit.jupiter.api.Test;38import org.junit.jupiter.api.extension.ExtendWith;39import org.junit.jupiter.extensions.TempDirectory;40import org.junit.jupiter.extensions.TempDirectory.Root;41import org.junit.jupiter.params.ParameterizedTest;42import org.junit.jupiter.params.provider.Arguments;43import org.junit.jupiter.params.provider.MethodSource;44import org.junit.platform.commons.util.PreconditionViolationException;45import org.junit.platform.commons.util.ReflectionUtils;46/**47 * Unit tests for {@link DiscoverySelectors}.48 *49 * @since 1.050 */51class DiscoverySelectorsTests {52 @Test53 void selectUriByName() {54 assertThrows(PreconditionViolationException.class, () -> selectUri((String) null));55 assertThrows(PreconditionViolationException.class, () -> selectUri(" "));56 assertThrows(PreconditionViolationException.class, () -> selectUri("foo:"));57 String uri = "http://junit.org";58 UriSelector selector = selectUri(uri);59 assertEquals(uri, selector.getUri().toString());60 }61 @Test62 void selectUriByURI() throws Exception {63 assertThrows(PreconditionViolationException.class, () -> selectUri((URI) null));64 assertThrows(PreconditionViolationException.class, () -> selectUri(" "));65 URI uri = new URI("http://junit.org");66 UriSelector selector = selectUri(uri);67 assertEquals(uri, selector.getUri());68 }69 @Test70 void selectFileByName() {71 assertThrows(PreconditionViolationException.class, () -> selectFile((String) null));72 assertThrows(PreconditionViolationException.class, () -> selectFile(" "));73 String path = "src/test/resources/do_not_delete_me.txt";74 FileSelector selector = selectFile(path);75 assertEquals(path, selector.getRawPath());76 assertEquals(new File(path), selector.getFile());77 assertEquals(Paths.get(path), selector.getPath());78 }79 @Test80 void selectFileByFileReference() throws Exception {81 assertThrows(PreconditionViolationException.class, () -> selectFile((File) null));82 assertThrows(PreconditionViolationException.class, () -> selectFile(new File("bogus/nonexistent.txt")));83 File currentDir = new File(".").getCanonicalFile();84 File relativeDir = new File("..", currentDir.getName());85 File file = new File(relativeDir, "src/test/resources/do_not_delete_me.txt");86 String path = file.getCanonicalFile().getPath();87 FileSelector selector = selectFile(file);88 assertEquals(path, selector.getRawPath());89 assertEquals(file.getCanonicalFile(), selector.getFile());90 assertEquals(Paths.get(path), selector.getPath());91 }92 @Test93 void selectDirectoryByName() {94 assertThrows(PreconditionViolationException.class, () -> selectDirectory((String) null));95 assertThrows(PreconditionViolationException.class, () -> selectDirectory(" "));96 String path = "src/test/resources";97 DirectorySelector selector = selectDirectory(path);98 assertEquals(path, selector.getRawPath());99 assertEquals(new File(path), selector.getDirectory());100 assertEquals(Paths.get(path), selector.getPath());101 }102 @Test103 void selectDirectoryByFileReference() throws Exception {104 assertThrows(PreconditionViolationException.class, () -> selectDirectory((File) null));105 assertThrows(PreconditionViolationException.class, () -> selectDirectory(new File("bogus/nonexistent")));106 File currentDir = new File(".").getCanonicalFile();107 File relativeDir = new File("..", currentDir.getName());108 File directory = new File(relativeDir, "src/test/resources");109 String path = directory.getCanonicalFile().getPath();110 DirectorySelector selector = selectDirectory(directory);111 assertEquals(path, selector.getRawPath());112 assertEquals(directory.getCanonicalFile(), selector.getDirectory());113 assertEquals(Paths.get(path), selector.getPath());114 }115 @Test116 void selectClasspathResources() {117 assertThrows(PreconditionViolationException.class, () -> selectClasspathResource(null));118 assertThrows(PreconditionViolationException.class, () -> selectClasspathResource(""));119 assertThrows(PreconditionViolationException.class, () -> selectClasspathResource(" "));120 assertThrows(PreconditionViolationException.class, () -> selectClasspathResource("\t"));121 // with unnecessary "/" prefix122 ClasspathResourceSelector selector = selectClasspathResource("/foo/bar/spec.xml");123 assertEquals("foo/bar/spec.xml", selector.getClasspathResourceName());124 // standard use case125 selector = selectClasspathResource("A/B/C/spec.json");126 assertEquals("A/B/C/spec.json", selector.getClasspathResourceName());127 }128 @Test129 void selectModuleByName() {130 ModuleSelector selector = selectModule("java.base");131 assertEquals("java.base", selector.getModuleName());132 }133 @Test134 void selectModuleByNamePreconditions() {135 assertThrows(PreconditionViolationException.class, () -> selectModule(null));136 assertThrows(PreconditionViolationException.class, () -> selectModule(""));137 assertThrows(PreconditionViolationException.class, () -> selectModule(" "));138 }139 @Test140 void selectModulesByNames() {141 List<ModuleSelector> selectors = selectModules(new HashSet<>(Arrays.asList("a", "b")));142 List<String> names = selectors.stream().map(ModuleSelector::getModuleName).collect(Collectors.toList());143 assertThat(names).containsExactlyInAnyOrder("b", "a");144 }145 @Test146 void selectModulesByNamesPreconditions() {147 assertThrows(PreconditionViolationException.class, () -> selectModules(null));148 assertThrows(PreconditionViolationException.class, () -> selectModules(new HashSet<>(Arrays.asList("a", " "))));149 }150 @Test151 void selectPackageByName() {152 PackageSelector selector = selectPackage(getClass().getPackage().getName());153 assertEquals(getClass().getPackage().getName(), selector.getPackageName());154 }155 @Test156 void selectClassByName() {157 ClassSelector selector = selectClass(getClass().getName());158 assertEquals(getClass(), selector.getJavaClass());159 }160 @Test161 void selectMethodByClassNameAndMethodNamePreconditions() {162 assertThrows(PreconditionViolationException.class, () -> selectMethod("TestClass", null));163 assertThrows(PreconditionViolationException.class, () -> selectMethod("TestClass", ""));164 assertThrows(PreconditionViolationException.class, () -> selectMethod("TestClass", " "));165 assertThrows(PreconditionViolationException.class, () -> selectMethod((String) null, "method"));166 assertThrows(PreconditionViolationException.class, () -> selectMethod("", "method"));167 assertThrows(PreconditionViolationException.class, () -> selectMethod(" ", "method"));168 }169 @Test170 void selectMethodByClassNameMethodNameAndMethodParameterTypesPreconditions() {171 assertThrows(PreconditionViolationException.class, () -> selectMethod("TestClass", null, "int"));172 assertThrows(PreconditionViolationException.class, () -> selectMethod("TestClass", "", "int"));173 assertThrows(PreconditionViolationException.class, () -> selectMethod("TestClass", " ", "int"));174 assertThrows(PreconditionViolationException.class, () -> selectMethod((String) null, "method", "int"));175 assertThrows(PreconditionViolationException.class, () -> selectMethod("", "method", "int"));176 assertThrows(PreconditionViolationException.class, () -> selectMethod(" ", "method", "int"));177 assertThrows(PreconditionViolationException.class, () -> selectMethod("TestClass", "method", null));178 }179 @Test180 void selectMethodByClassAndMethodNamePreconditions() {181 assertThrows(PreconditionViolationException.class, () -> selectMethod(getClass(), (String) null));182 assertThrows(PreconditionViolationException.class, () -> selectMethod(getClass(), ""));183 assertThrows(PreconditionViolationException.class, () -> selectMethod(getClass(), " "));184 assertThrows(PreconditionViolationException.class, () -> selectMethod((Class<?>) null, "method"));185 assertThrows(PreconditionViolationException.class, () -> selectMethod("", "method"));186 assertThrows(PreconditionViolationException.class, () -> selectMethod(" ", "method"));187 }188 @Test189 void selectMethodByClassMethodNameAndMethodParameterTypesPreconditions() {190 assertThrows(PreconditionViolationException.class, () -> selectMethod((Class<?>) null, "method", "int"));191 assertThrows(PreconditionViolationException.class, () -> selectMethod(getClass(), null, "int"));192 assertThrows(PreconditionViolationException.class, () -> selectMethod(getClass(), "", "int"));193 assertThrows(PreconditionViolationException.class, () -> selectMethod(getClass(), " ", "int"));194 assertThrows(PreconditionViolationException.class, () -> selectMethod(getClass(), "method", null));195 }196 @Test197 void selectMethodByClassAndMethodPreconditions() {198 Method method = getClass().getDeclaredMethods()[0];199 assertThrows(PreconditionViolationException.class, () -> selectMethod(null, method));200 assertThrows(PreconditionViolationException.class, () -> selectMethod(getClass(), (Method) null));201 }202 @ParameterizedTest(name = "FQMN: ''{0}''")203 @MethodSource("invalidFullyQualifiedMethodNames")204 void selectMethodByFullyQualifiedNamePreconditions(String fqmn, String message) {205 Exception exception = assertThrows(PreconditionViolationException.class, () -> selectMethod(fqmn));206 assertThat(exception).hasMessageContaining(message);207 }208 static Stream<Arguments> invalidFullyQualifiedMethodNames() {209 // @formatter:off210 return Stream.of(211 arguments(null, "must not be null or blank"),212 arguments("", "must not be null or blank"),213 arguments(" ", "must not be null or blank"),214 arguments("com.example", "not a valid fully qualified method name"),215 arguments("com.example.Foo", "not a valid fully qualified method name"),216 arguments("method", "not a valid fully qualified method name"),217 arguments("#method", "not a valid fully qualified method name"),218 arguments("#method()", "not a valid fully qualified method name"),219 arguments("#method(int)", "not a valid fully qualified method name"),...

Full Screen

Full Screen

Source:AssertTimeoutAssertionsTests.java Github

copy

Full Screen

...12import static org.junit.jupiter.api.AssertionTestUtils.assertMessageEquals;13import static org.junit.jupiter.api.AssertionTestUtils.assertMessageStartsWith;14import static org.junit.jupiter.api.Assertions.assertEquals;15import static org.junit.jupiter.api.Assertions.assertFalse;16import static org.junit.jupiter.api.Assertions.assertThrows;17import static org.junit.jupiter.api.Assertions.assertTimeout;18import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;19import static org.junit.jupiter.api.Assertions.assertTrue;20import static org.junit.jupiter.api.Assertions.fail;21import java.util.concurrent.atomic.AtomicBoolean;22import org.junit.jupiter.api.function.Executable;23import org.junit.platform.commons.util.ExceptionUtils;24import org.opentest4j.AssertionFailedError;25/**26 * Unit tests for JUnit Jupiter {@link Assertions}.27 *28 * @since 5.029 */30class AssertTimeoutAssertionsTests {31 private static ThreadLocal<AtomicBoolean> changed = ThreadLocal.withInitial(() -> new AtomicBoolean(false));32 private final Executable nix = () -> {33 };34 // --- executable ----------------------------------------------------------35 @Test36 void assertTimeoutForExecutableThatCompletesBeforeTheTimeout() {37 changed.get().set(false);38 assertTimeout(ofMillis(500), () -> changed.get().set(true));39 assertTrue(changed.get().get(), "should have executed in the same thread");40 assertTimeout(ofMillis(500), nix, "message");41 assertTimeout(ofMillis(500), nix, () -> "message");42 }43 @Test44 void assertTimeoutForExecutableThatThrowsAnException() {45 RuntimeException exception = assertThrows(RuntimeException.class, () -> assertTimeout(ofMillis(500), () -> {46 throw new RuntimeException("not this time");47 }));48 assertMessageEquals(exception, "not this time");49 }50 @Test51 void assertTimeoutForExecutableThatThrowsAnAssertionFailedError() {52 AssertionFailedError exception = assertThrows(AssertionFailedError.class,53 () -> assertTimeout(ofMillis(500), () -> fail("enigma")));54 assertMessageEquals(exception, "enigma");55 }56 @Test57 void assertTimeoutForExecutableThatCompletesAfterTheTimeout() {58 AssertionFailedError error = assertThrows(AssertionFailedError.class,59 () -> assertTimeout(ofMillis(10), this::nap));60 assertMessageStartsWith(error, "execution exceeded timeout of 10 ms by");61 }62 @Test63 void assertTimeoutWithMessageForExecutableThatCompletesAfterTheTimeout() {64 AssertionFailedError error = assertThrows(AssertionFailedError.class,65 () -> assertTimeout(ofMillis(10), this::nap, "Tempus Fugit"));66 assertMessageStartsWith(error, "Tempus Fugit ==> execution exceeded timeout of 10 ms by");67 }68 @Test69 void assertTimeoutWithMessageSupplierForExecutableThatCompletesAfterTheTimeout() {70 AssertionFailedError error = assertThrows(AssertionFailedError.class,71 () -> assertTimeout(ofMillis(10), this::nap, () -> "Tempus" + " " + "Fugit"));72 assertMessageStartsWith(error, "Tempus Fugit ==> execution exceeded timeout of 10 ms by");73 }74 // --- supplier ------------------------------------------------------------75 @Test76 void assertTimeoutForSupplierThatCompletesBeforeTheTimeout() {77 changed.get().set(false);78 String result = assertTimeout(ofMillis(500), () -> {79 changed.get().set(true);80 return "Tempus Fugit";81 });82 assertTrue(changed.get().get(), "should have executed in the same thread");83 assertEquals("Tempus Fugit", result);84 assertEquals("Tempus Fugit", assertTimeout(ofMillis(500), () -> "Tempus Fugit", "message"));85 assertEquals("Tempus Fugit", assertTimeout(ofMillis(500), () -> "Tempus Fugit", () -> "message"));86 }87 @Test88 void assertTimeoutForSupplierThatThrowsAnException() {89 RuntimeException exception = assertThrows(RuntimeException.class, () -> {90 assertTimeout(ofMillis(500), () -> {91 ExceptionUtils.throwAsUncheckedException(new RuntimeException("not this time"));92 return "Tempus Fugit";93 });94 });95 assertMessageEquals(exception, "not this time");96 }97 @Test98 void assertTimeoutForSupplierThatThrowsAnAssertionFailedError() {99 AssertionFailedError exception = assertThrows(AssertionFailedError.class, () -> {100 assertTimeout(ofMillis(500), () -> {101 fail("enigma");102 return "Tempus Fugit";103 });104 });105 assertMessageEquals(exception, "enigma");106 }107 @Test108 void assertTimeoutForSupplierThatCompletesAfterTheTimeout() {109 AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> {110 assertTimeout(ofMillis(10), () -> {111 nap();112 return "Tempus Fugit";113 });114 });115 assertMessageStartsWith(error, "execution exceeded timeout of 10 ms by");116 }117 @Test118 void assertTimeoutWithMessageForSupplierThatCompletesAfterTheTimeout() {119 AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> {120 assertTimeout(ofMillis(10), () -> {121 nap();122 return "Tempus Fugit";123 }, "Tempus Fugit");124 });125 assertMessageStartsWith(error, "Tempus Fugit ==> execution exceeded timeout of 10 ms by");126 }127 @Test128 void assertTimeoutWithMessageSupplierForSupplierThatCompletesAfterTheTimeout() {129 AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> {130 assertTimeout(ofMillis(10), () -> {131 nap();132 return "Tempus Fugit";133 }, () -> "Tempus" + " " + "Fugit");134 });135 assertMessageStartsWith(error, "Tempus Fugit ==> execution exceeded timeout of 10 ms by");136 }137 // -- executable - preemptively ---138 @Test139 void assertTimeoutPreemptivelyForExecutableThatCompletesBeforeTheTimeout() {140 changed.get().set(false);141 assertTimeoutPreemptively(ofMillis(500), () -> changed.get().set(true));142 assertFalse(changed.get().get(), "should have executed in a different thread");143 assertTimeoutPreemptively(ofMillis(500), nix, "message");144 assertTimeoutPreemptively(ofMillis(500), nix, () -> "message");145 }146 @Test147 void assertTimeoutPreemptivelyForExecutableThatThrowsAnException() {148 RuntimeException exception = assertThrows(RuntimeException.class,149 () -> assertTimeoutPreemptively(ofMillis(500), () -> {150 throw new RuntimeException("not this time");151 }));152 assertMessageEquals(exception, "not this time");153 }154 @Test155 void assertTimeoutPreemptivelyForExecutableThatThrowsAnAssertionFailedError() {156 AssertionFailedError exception = assertThrows(AssertionFailedError.class,157 () -> assertTimeoutPreemptively(ofMillis(500), () -> fail("enigma")));158 assertMessageEquals(exception, "enigma");159 }160 @Test161 void assertTimeoutPreemptivelyForExecutableThatCompletesAfterTheTimeout() {162 AssertionFailedError error = assertThrows(AssertionFailedError.class,163 () -> assertTimeoutPreemptively(ofMillis(10), this::nap));164 assertMessageEquals(error, "execution timed out after 10 ms");165 }166 @Test167 void assertTimeoutPreemptivelyWithMessageForExecutableThatCompletesAfterTheTimeout() {168 AssertionFailedError error = assertThrows(AssertionFailedError.class,169 () -> assertTimeoutPreemptively(ofMillis(10), this::nap, "Tempus Fugit"));170 assertMessageEquals(error, "Tempus Fugit ==> execution timed out after 10 ms");171 }172 @Test173 void assertTimeoutPreemptivelyWithMessageSupplierForExecutableThatCompletesAfterTheTimeout() {174 AssertionFailedError error = assertThrows(AssertionFailedError.class,175 () -> assertTimeoutPreemptively(ofMillis(10), this::nap, () -> "Tempus" + " " + "Fugit"));176 assertMessageEquals(error, "Tempus Fugit ==> execution timed out after 10 ms");177 }178 @Test179 void assertTimeoutPreemptivelyWithMessageSupplierForExecutableThatCompletesBeforeTheTimeout() {180 assertTimeoutPreemptively(ofMillis(500), nix, () -> "Tempus" + " " + "Fugit");181 }182 // -- supplier - preemptively ---183 @Test184 void assertTimeoutPreemptivelyForSupplierThatCompletesBeforeTheTimeout() {185 changed.get().set(false);186 String result = assertTimeoutPreemptively(ofMillis(500), () -> {187 changed.get().set(true);188 return "Tempus Fugit";189 });190 assertFalse(changed.get().get(), "should have executed in a different thread");191 assertEquals("Tempus Fugit", result);192 assertEquals("Tempus Fugit", assertTimeoutPreemptively(ofMillis(500), () -> "Tempus Fugit", "message"));193 assertEquals("Tempus Fugit", assertTimeoutPreemptively(ofMillis(500), () -> "Tempus Fugit", () -> "message"));194 }195 @Test196 void assertTimeoutPreemptivelyForSupplierThatThrowsAnException() {197 RuntimeException exception = assertThrows(RuntimeException.class, () -> {198 assertTimeoutPreemptively(ofMillis(500), () -> {199 ExceptionUtils.throwAsUncheckedException(new RuntimeException("not this time"));200 return "Tempus Fugit";201 });202 });203 assertMessageEquals(exception, "not this time");204 }205 @Test206 void assertTimeoutPreemptivelyForSupplierThatThrowsAnAssertionFailedError() {207 AssertionFailedError exception = assertThrows(AssertionFailedError.class, () -> {208 assertTimeoutPreemptively(ofMillis(500), () -> {209 fail("enigma");210 return "Tempus Fugit";211 });212 });213 assertMessageEquals(exception, "enigma");214 }215 @Test216 void assertTimeoutPreemptivelyForSupplierThatCompletesAfterTheTimeout() {217 AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> {218 assertTimeoutPreemptively(ofMillis(10), () -> {219 nap();220 return "Tempus Fugit";221 });222 });223 assertMessageEquals(error, "execution timed out after 10 ms");224 }225 @Test226 void assertTimeoutPreemptivelyWithMessageForSupplierThatCompletesAfterTheTimeout() {227 AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> {228 assertTimeoutPreemptively(ofMillis(10), () -> {229 nap();230 return "Tempus Fugit";231 }, "Tempus Fugit");232 });233 assertMessageEquals(error, "Tempus Fugit ==> execution timed out after 10 ms");234 }235 @Test236 void assertTimeoutPreemptivelyWithMessageSupplierForSupplierThatCompletesAfterTheTimeout() {237 AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> {238 assertTimeoutPreemptively(ofMillis(10), () -> {239 nap();240 return "Tempus Fugit";241 }, () -> "Tempus" + " " + "Fugit");242 });243 assertMessageEquals(error, "Tempus Fugit ==> execution timed out after 10 ms");244 }245 /**246 * Take a nap for 100 milliseconds.247 */248 private void nap() throws InterruptedException {249 Thread.sleep(100);250 }251}...

Full Screen

Full Screen

Source:AssertThrowsAssertionsTests.java Github

copy

Full Screen

...13import static org.junit.jupiter.api.AssertionTestUtils.assertMessageStartsWith;14import static org.junit.jupiter.api.AssertionTestUtils.expectAssertionFailedError;15import static org.junit.jupiter.api.Assertions.assertEquals;16import static org.junit.jupiter.api.Assertions.assertNotNull;17import static org.junit.jupiter.api.Assertions.assertThrows;18import java.io.IOException;19import java.net.URL;20import java.net.URLClassLoader;21import java.util.concurrent.ExecutionException;22import java.util.concurrent.FutureTask;23import org.junit.jupiter.api.function.Executable;24import org.opentest4j.AssertionFailedError;25/**26 * Unit tests for JUnit Jupiter {@link Assertions}.27 *28 * @since 5.029 */30class AssertThrowsAssertionsTests {31 private static final Executable nix = () -> {32 };33 @Test34 void assertThrowsWithMethodReferenceForNonVoidReturnType() {35 FutureTask<String> future = new FutureTask<>(() -> {36 throw new RuntimeException("boom");37 });38 future.run();39 ExecutionException exception = assertThrows(ExecutionException.class, future::get);40 assertEquals("boom", exception.getCause().getMessage());41 }42 @Test43 void assertThrowsWithMethodReferenceForVoidReturnType() {44 var object = new Object();45 IllegalMonitorStateException exception;46 exception = assertThrows(IllegalMonitorStateException.class, object::notify);47 assertNotNull(exception);48 // Note that Object.wait(...) is an overloaded method with a void return type49 exception = assertThrows(IllegalMonitorStateException.class, object::wait);50 assertNotNull(exception);51 }52 @Test53 void assertThrowsWithExecutableThatThrowsThrowable() {54 EnigmaThrowable enigmaThrowable = assertThrows(EnigmaThrowable.class, (Executable) () -> {55 throw new EnigmaThrowable();56 });57 assertNotNull(enigmaThrowable);58 }59 @Test60 void assertThrowsWithExecutableThatThrowsThrowableWithMessage() {61 EnigmaThrowable enigmaThrowable = assertThrows(EnigmaThrowable.class, (Executable) () -> {62 throw new EnigmaThrowable();63 }, "message");64 assertNotNull(enigmaThrowable);65 }66 @Test67 void assertThrowsWithExecutableThatThrowsThrowableWithMessageSupplier() {68 EnigmaThrowable enigmaThrowable = assertThrows(EnigmaThrowable.class, (Executable) () -> {69 throw new EnigmaThrowable();70 }, () -> "message");71 assertNotNull(enigmaThrowable);72 }73 @Test74 void assertThrowsWithExecutableThatThrowsCheckedException() {75 IOException exception = assertThrows(IOException.class, (Executable) () -> {76 throw new IOException();77 });78 assertNotNull(exception);79 }80 @Test81 void assertThrowsWithExecutableThatThrowsRuntimeException() {82 IllegalStateException illegalStateException = assertThrows(IllegalStateException.class, (Executable) () -> {83 throw new IllegalStateException();84 });85 assertNotNull(illegalStateException);86 }87 @Test88 void assertThrowsWithExecutableThatThrowsError() {89 StackOverflowError stackOverflowError = assertThrows(StackOverflowError.class,90 (Executable) AssertionTestUtils::recurseIndefinitely);91 assertNotNull(stackOverflowError);92 }93 @Test94 void assertThrowsWithExecutableThatDoesNotThrowAnException() {95 try {96 assertThrows(IllegalStateException.class, nix);97 expectAssertionFailedError();98 }99 catch (AssertionFailedError ex) {100 assertMessageEquals(ex, "Expected java.lang.IllegalStateException to be thrown, but nothing was thrown.");101 }102 }103 @Test104 void assertThrowsWithExecutableThatDoesNotThrowAnExceptionWithMessageString() {105 try {106 assertThrows(IOException.class, nix, "Custom message");107 expectAssertionFailedError();108 }109 catch (AssertionError ex) {110 assertMessageEquals(ex,111 "Custom message ==> Expected java.io.IOException to be thrown, but nothing was thrown.");112 }113 }114 @Test115 void assertThrowsWithExecutableThatDoesNotThrowAnExceptionWithMessageSupplier() {116 try {117 assertThrows(IOException.class, nix, () -> "Custom message");118 expectAssertionFailedError();119 }120 catch (AssertionError ex) {121 assertMessageEquals(ex,122 "Custom message ==> Expected java.io.IOException to be thrown, but nothing was thrown.");123 }124 }125 @Test126 void assertThrowsWithExecutableThatThrowsAnUnexpectedException() {127 try {128 assertThrows(IllegalStateException.class, (Executable) () -> {129 throw new NumberFormatException();130 });131 expectAssertionFailedError();132 }133 catch (AssertionFailedError ex) {134 assertMessageStartsWith(ex, "Unexpected exception type thrown ==> ");135 assertMessageContains(ex, "expected: <java.lang.IllegalStateException>");136 assertMessageContains(ex, "but was: <java.lang.NumberFormatException>");137 }138 }139 @Test140 void assertThrowsWithExecutableThatThrowsAnUnexpectedExceptionWithMessageString() {141 try {142 assertThrows(IllegalStateException.class, (Executable) () -> {143 throw new NumberFormatException();144 }, "Custom message");145 expectAssertionFailedError();146 }147 catch (AssertionFailedError ex) {148 // Should look something like this:149 // Custom message ==> Unexpected exception type thrown ==> expected: <java.lang.IllegalStateException> but was: <java.lang.NumberFormatException>150 assertMessageStartsWith(ex, "Custom message ==> ");151 assertMessageContains(ex, "Unexpected exception type thrown ==> ");152 assertMessageContains(ex, "expected: <java.lang.IllegalStateException>");153 assertMessageContains(ex, "but was: <java.lang.NumberFormatException>");154 }155 }156 @Test157 void assertThrowsWithExecutableThatThrowsAnUnexpectedExceptionWithMessageSupplier() {158 try {159 assertThrows(IllegalStateException.class, (Executable) () -> {160 throw new NumberFormatException();161 }, () -> "Custom message");162 expectAssertionFailedError();163 }164 catch (AssertionFailedError ex) {165 // Should look something like this:166 // Custom message ==> Unexpected exception type thrown ==> expected: <java.lang.IllegalStateException> but was: <java.lang.NumberFormatException>167 assertMessageStartsWith(ex, "Custom message ==> ");168 assertMessageContains(ex, "Unexpected exception type thrown ==> ");169 assertMessageContains(ex, "expected: <java.lang.IllegalStateException>");170 assertMessageContains(ex, "but was: <java.lang.NumberFormatException>");171 }172 }173 @Test174 @SuppressWarnings("serial")175 void assertThrowsWithExecutableThatThrowsInstanceOfAnonymousInnerClassAsUnexpectedException() {176 try {177 assertThrows(IllegalStateException.class, (Executable) () -> {178 throw new NumberFormatException() {179 };180 });181 expectAssertionFailedError();182 }183 catch (AssertionFailedError ex) {184 assertMessageStartsWith(ex, "Unexpected exception type thrown ==> ");185 assertMessageContains(ex, "expected: <java.lang.IllegalStateException>");186 // As of the time of this writing, the class name of the above anonymous inner187 // class is org.junit.jupiter.api.AssertionsAssertThrowsTests$2; however, hard188 // coding "$2" is fragile. So we just check for the presence of the "$"189 // appended to this class's name.190 assertMessageContains(ex, "but was: <" + getClass().getName() + "$");191 }192 }193 @Test194 void assertThrowsWithExecutableThatThrowsInstanceOfStaticNestedClassAsUnexpectedException() {195 try {196 assertThrows(IllegalStateException.class, (Executable) () -> {197 throw new LocalException();198 });199 expectAssertionFailedError();200 }201 catch (AssertionFailedError ex) {202 assertMessageStartsWith(ex, "Unexpected exception type thrown ==> ");203 assertMessageContains(ex, "expected: <java.lang.IllegalStateException>");204 // The following verifies that the canonical name is used (i.e., "." instead of "$").205 assertMessageContains(ex, "but was: <" + LocalException.class.getName().replace("$", ".") + ">");206 }207 }208 @Test209 @SuppressWarnings("unchecked")210 void assertThrowsWithExecutableThatThrowsSameExceptionTypeFromDifferentClassLoader() throws Exception {211 try (EnigmaClassLoader enigmaClassLoader = new EnigmaClassLoader()) {212 // Load expected exception type from different class loader213 Class<? extends Throwable> enigmaThrowableClass = (Class<? extends Throwable>) enigmaClassLoader.loadClass(214 EnigmaThrowable.class.getName());215 try {216 assertThrows(enigmaThrowableClass, (Executable) () -> {217 throw new EnigmaThrowable();218 });219 expectAssertionFailedError();220 }221 catch (AssertionFailedError ex) {222 // Example Output:223 //224 // Unexpected exception type thrown ==>225 // expected: <org.junit.jupiter.api.EnigmaThrowable@5d3411d>226 // but was: <org.junit.jupiter.api.EnigmaThrowable@2471cca7>227 assertMessageStartsWith(ex, "Unexpected exception type thrown ==> ");228 // The presence of the "@" sign is sufficient to indicate that the hash was229 // generated to disambiguate between the two identical class names.230 assertMessageContains(ex, "expected: <org.junit.jupiter.api.EnigmaThrowable@");...

Full Screen

Full Screen

Source:PreconditionsTests.java Github

copy

Full Screen

...11import static java.util.Collections.emptyList;12import static java.util.Collections.singletonList;13import static org.junit.jupiter.api.Assertions.assertEquals;14import static org.junit.jupiter.api.Assertions.assertSame;15import static org.junit.jupiter.api.Assertions.assertThrows;16import static org.junit.platform.commons.util.Preconditions.condition;17import static org.junit.platform.commons.util.Preconditions.containsNoNullElements;18import static org.junit.platform.commons.util.Preconditions.notBlank;19import static org.junit.platform.commons.util.Preconditions.notEmpty;20import static org.junit.platform.commons.util.Preconditions.notNull;21import java.util.Arrays;22import java.util.Collection;23import java.util.List;24import org.junit.jupiter.api.Test;25/**26 * Unit tests for {@link Preconditions}.27 *28 * @since 1.029 */30class PreconditionsTests {31 @Test32 void notNullPassesForNonNullObject() {33 Object object = new Object();34 Object nonNullObject = notNull(object, "message");35 assertSame(object, nonNullObject);36 }37 @Test38 void notNullThrowsForNullObject() {39 String message = "argument is null";40 PreconditionViolationException exception = assertThrows(PreconditionViolationException.class,41 () -> notNull(null, message));42 assertEquals(message, exception.getMessage());43 }44 @Test45 void notNullThrowsForNullObjectAndMessageSupplier() {46 String message = "argument is null";47 Object object = null;48 PreconditionViolationException exception = assertThrows(PreconditionViolationException.class,49 () -> notNull(object, () -> message));50 assertEquals(message, exception.getMessage());51 }52 @Test53 void notEmptyPassesForNonEmptyArray() {54 String[] array = new String[] { "a", "b", "c" };55 String[] nonEmptyArray = notEmpty(array, () -> "should not fail");56 assertSame(array, nonEmptyArray);57 }58 @Test59 void notEmptyPassesForNonEmptyCollection() {60 Collection<String> collection = Arrays.asList("a", "b", "c");61 Collection<String> nonEmptyCollection = notEmpty(collection, () -> "should not fail");62 assertSame(collection, nonEmptyCollection);63 }64 @Test65 void notEmptyPassesForArrayWithNullElements() {66 notEmpty(new String[] { null }, "message");67 }68 @Test69 void notEmptyPassesForCollectionWithNullElements() {70 notEmpty(singletonList(null), "message");71 }72 @Test73 void notEmptyThrowsForNullArray() {74 String message = "array is empty";75 PreconditionViolationException exception = assertThrows(PreconditionViolationException.class,76 () -> notEmpty((Object[]) null, message));77 assertEquals(message, exception.getMessage());78 }79 @Test80 void notEmptyThrowsForNullCollection() {81 String message = "collection is empty";82 PreconditionViolationException exception = assertThrows(PreconditionViolationException.class,83 () -> notEmpty((Collection<?>) null, message));84 assertEquals(message, exception.getMessage());85 }86 @Test87 void notEmptyThrowsForEmptyArray() {88 String message = "array is empty";89 PreconditionViolationException exception = assertThrows(PreconditionViolationException.class,90 () -> notEmpty(new Object[0], message));91 assertEquals(message, exception.getMessage());92 }93 @Test94 void notEmptyThrowsForEmptyCollection() {95 String message = "collection is empty";96 PreconditionViolationException exception = assertThrows(PreconditionViolationException.class,97 () -> notEmpty(emptyList(), message));98 assertEquals(message, exception.getMessage());99 }100 @Test101 void containsNoNullElementsPassesForArrayThatIsNullOrEmpty() {102 containsNoNullElements((Object[]) null, "array is null");103 containsNoNullElements((Object[]) null, () -> "array is null");104 containsNoNullElements(new Object[0], "array is empty");105 containsNoNullElements(new Object[0], () -> "array is empty");106 }107 @Test108 void containsNoNullElementsPassesForCollectionThatIsNullOrEmpty() {109 containsNoNullElements((List<?>) null, "collection is null");110 containsNoNullElements(emptyList(), "collection is empty");111 containsNoNullElements((List<?>) null, () -> "collection is null");112 containsNoNullElements(emptyList(), () -> "collection is empty");113 }114 @Test115 void containsNoNullElementsPassesForArrayContainingNonNullElements() {116 String[] input = new String[] { "a", "b", "c" };117 String[] output = containsNoNullElements(input, "message");118 assertSame(input, output);119 }120 @Test121 void containsNoNullElementsPassesForCollectionContainingNonNullElements() {122 Collection<String> input = Arrays.asList("a", "b", "c");123 Collection<String> output = containsNoNullElements(input, "message");124 assertSame(input, output);125 output = containsNoNullElements(input, () -> "message");126 assertSame(input, output);127 }128 @Test129 void containsNoNullElementsThrowsForArrayContainingNullElements() {130 String message = "array contains null elements";131 Object[] array = { new Object(), null, new Object() };132 PreconditionViolationException exception = assertThrows(PreconditionViolationException.class,133 () -> containsNoNullElements(array, message));134 assertEquals(message, exception.getMessage());135 }136 @Test137 void containsNoNullElementsThrowsForCollectionContainingNullElements() {138 String message = "collection contains null elements";139 PreconditionViolationException exception = assertThrows(PreconditionViolationException.class,140 () -> containsNoNullElements(singletonList(null), message));141 assertEquals(message, exception.getMessage());142 }143 @Test144 void notBlankPassesForNonBlankString() {145 String string = "abc";146 String nonBlankString = notBlank(string, "message");147 assertSame(string, nonBlankString);148 }149 @Test150 void notBlankThrowsForNullString() {151 String message = "string shouldn't be blank";152 PreconditionViolationException exception = assertThrows(PreconditionViolationException.class,153 () -> notBlank(null, message));154 assertEquals(message, exception.getMessage());155 }156 @Test157 void notBlankThrowsForNullStringWithMessageSupplier() {158 String message = "string shouldn't be blank";159 PreconditionViolationException exception = assertThrows(PreconditionViolationException.class,160 () -> notBlank(null, () -> message));161 assertEquals(message, exception.getMessage());162 }163 @Test164 void notBlankThrowsForEmptyString() {165 String message = "string shouldn't be blank";166 PreconditionViolationException exception = assertThrows(PreconditionViolationException.class,167 () -> notBlank("", message));168 assertEquals(message, exception.getMessage());169 }170 @Test171 void notBlankThrowsForEmptyStringWithMessageSupplier() {172 String message = "string shouldn't be blank";173 PreconditionViolationException exception = assertThrows(PreconditionViolationException.class,174 () -> notBlank("", () -> message));175 assertEquals(message, exception.getMessage());176 }177 @Test178 void notBlankThrowsForBlankString() {179 String message = "string shouldn't be blank";180 PreconditionViolationException exception = assertThrows(PreconditionViolationException.class,181 () -> notBlank(" ", message));182 assertEquals(message, exception.getMessage());183 }184 @Test185 void notBlankThrowsForBlankStringWithMessageSupplier() {186 String message = "string shouldn't be blank";187 PreconditionViolationException exception = assertThrows(PreconditionViolationException.class,188 () -> notBlank(" ", () -> message));189 assertEquals(message, exception.getMessage());190 }191 @Test192 void conditionPassesForTruePredicate() {193 condition(true, "error message");194 }195 @Test196 void conditionPassesForTruePredicateWithMessageSupplier() {197 condition(true, () -> "error message");198 }199 @Test200 void conditionThrowsForFalsePredicate() {201 String message = "condition does not hold";202 PreconditionViolationException exception = assertThrows(PreconditionViolationException.class,203 () -> condition(false, message));204 assertEquals(message, exception.getMessage());205 }206 @Test207 void conditionThrowsForFalsePredicateWithMessageSupplier() {208 String message = "condition does not hold";209 PreconditionViolationException exception = assertThrows(PreconditionViolationException.class,210 () -> condition(false, () -> message));211 assertEquals(message, exception.getMessage());212 }213}...

Full Screen

Full Screen

Source:PackageUtilsTests.java Github

copy

Full Screen

...9 */10package org.junit.platform.commons.util;11import static org.junit.jupiter.api.Assertions.assertEquals;12import static org.junit.jupiter.api.Assertions.assertFalse;13import static org.junit.jupiter.api.Assertions.assertThrows;14import static org.junit.jupiter.api.Assertions.assertTrue;15import static org.junit.jupiter.api.Assertions.fail;16import static org.junit.jupiter.api.DynamicTest.dynamicTest;17import java.util.Arrays;18import java.util.List;19import java.util.function.Function;20import org.junit.jupiter.api.DynamicTest;21import org.junit.jupiter.api.Test;22import org.junit.jupiter.api.TestFactory;23import org.junit.jupiter.api.function.Executable;24import org.opentest4j.ValueWrapper;25/**26 * Unit tests for {@link PackageUtils}.27 *28 * @since 1.029 */30class PackageUtilsTests {31 @Test32 void assertPackageNameIsValidForValidPackageNames() {33 PackageUtils.assertPackageNameIsValid(""); // default package34 PackageUtils.assertPackageNameIsValid("non.existing.but.all.segments.are.syntactically.valid");35 }36 @Test37 void assertPackageNameIsValidForNullPackageName() {38 assertThrows(PreconditionViolationException.class, () -> PackageUtils.assertPackageNameIsValid(null));39 }40 @Test41 void assertPackageNameIsValidForWhitespacePackageName() {42 assertThrows(PreconditionViolationException.class, () -> PackageUtils.assertPackageNameIsValid(" "));43 }44 @Test45 void assertPackageNameIsValidForInvalidPackageNames() {46 assertThrows(PreconditionViolationException.class, () -> PackageUtils.assertPackageNameIsValid(".a"));47 assertThrows(PreconditionViolationException.class, () -> PackageUtils.assertPackageNameIsValid("a."));48 assertThrows(PreconditionViolationException.class, () -> PackageUtils.assertPackageNameIsValid("a..b"));49 assertThrows(PreconditionViolationException.class, () -> PackageUtils.assertPackageNameIsValid("byte.true"));50 }51 @Test52 void getAttributeWithNullType() {53 PreconditionViolationException exception = assertThrows(PreconditionViolationException.class,54 () -> PackageUtils.getAttribute(null, p -> "any"));55 assertEquals("type must not be null", exception.getMessage());56 }57 @Test58 void getAttributeWithNullFunction() {59 PreconditionViolationException exception = assertThrows(PreconditionViolationException.class,60 () -> PackageUtils.getAttribute(getClass(), (Function<Package, String>) null));61 assertEquals("function must not be null", exception.getMessage());62 }63 @Test64 void getAttributeWithFunctionReturningNullIsEmpty() {65 assertFalse(PackageUtils.getAttribute(ValueWrapper.class, p -> null).isPresent());66 }67 @Test68 void getAttributeFromDefaultPackageMemberIsEmpty() {69 Class<?> classInDefaultPackage = ReflectionUtils.loadClass("DefaultPackageTestCase").orElseGet(70 () -> fail("Could not load class from default package"));71 assertFalse(PackageUtils.getAttribute(classInDefaultPackage, Package::getSpecificationTitle).isPresent());72 }73 @TestFactory74 List<DynamicTest> attributesFromValueWrapperClassArePresent() {75 return Arrays.asList(dynamicTest("getName", isPresent(Package::getName)),76 dynamicTest("getImplementationTitle", isPresent(Package::getImplementationTitle)),77 dynamicTest("getImplementationVendor", isPresent(Package::getImplementationVendor)),78 dynamicTest("getImplementationVersion", isPresent(Package::getImplementationVersion)),79 dynamicTest("getSpecificationTitle", isPresent(Package::getSpecificationTitle)),80 dynamicTest("getSpecificationVendor", isPresent(Package::getSpecificationVendor)),81 dynamicTest("getSpecificationVersion", isPresent(Package::getSpecificationVersion)));82 }83 private Executable isPresent(Function<Package, String> function) {84 return () -> assertTrue(PackageUtils.getAttribute(ValueWrapper.class, function).isPresent());85 }86 @Test87 void getAttributeWithNullTypeAndName() {88 PreconditionViolationException exception = assertThrows(PreconditionViolationException.class,89 () -> PackageUtils.getAttribute(null, "foo"));90 assertEquals("type must not be null", exception.getMessage());91 }92 @Test93 void getAttributeWithNullName() {94 PreconditionViolationException exception = assertThrows(PreconditionViolationException.class,95 () -> PackageUtils.getAttribute(getClass(), (String) null));96 assertEquals("name must not be blank", exception.getMessage());97 }98 @Test99 void getAttributeWithEmptyName() {100 PreconditionViolationException exception = assertThrows(PreconditionViolationException.class,101 () -> PackageUtils.getAttribute(getClass(), ""));102 assertEquals("name must not be blank", exception.getMessage());103 }104}...

Full Screen

Full Screen

Source:ScriptTests.java Github

copy

Full Screen

...10package org.junit.jupiter.engine.script;11import static org.junit.jupiter.api.Assertions.assertEquals;12import static org.junit.jupiter.api.Assertions.assertNotEquals;13import static org.junit.jupiter.api.Assertions.assertNotNull;14import static org.junit.jupiter.api.Assertions.assertThrows;15import static org.junit.jupiter.api.DynamicTest.dynamicTest;16import java.lang.annotation.Annotation;17import java.util.stream.Stream;18import org.junit.jupiter.api.DynamicTest;19import org.junit.jupiter.api.Test;20import org.junit.jupiter.api.TestFactory;21import org.junit.jupiter.api.TestInfo;22import org.junit.platform.commons.JUnitException;23/**24 * Unit tests for {@link Script}.25 *26 * @since 5.127 */28class ScriptTests {29 @Test30 void constructorWithAllArguments() {31 Script script = new Script(Deprecated.class, "annotation", "engine", "source", "reason");32 assertEquals(Deprecated.class, script.getAnnotationType());33 assertEquals("annotation", script.getAnnotationAsString());34 assertEquals("engine", script.getEngine());35 assertEquals("source", script.getSource());36 assertEquals("reason", script.getReason());37 assertEquals("reason", script.toReasonString("unused result"));38 }39 @Test40 void constructorWithAnnotation(TestInfo info) {41 Annotation annotation = info.getTestMethod().orElseThrow(Error::new).getAnnotation(Test.class);42 Script script = new Script(annotation, "engine", "source", "reason");43 assertEquals(Test.class, script.getAnnotationType());44 assertEquals("@org.junit.jupiter.api.Test()", script.getAnnotationAsString());45 assertEquals("engine", script.getEngine());46 assertEquals("source", script.getSource());47 assertEquals("reason", script.getReason());48 assertEquals("reason", script.toReasonString("unused result"));49 }50 @TestFactory51 Stream<DynamicTest> preconditionsAreChecked(TestInfo info) {52 Annotation annotation = info.getTestMethod().orElseThrow(Error::new).getAnnotation(TestFactory.class);53 Class<JUnitException> expected = JUnitException.class;54 return Stream.of( //55 dynamicTest("0", () -> assertNotNull(new Script(annotation, "e", "s", "r"))), //56 dynamicTest("1", () -> assertThrows(expected, () -> new Script(null, "e", "s", "r"))), //57 // null is not allowed58 dynamicTest("2", () -> assertNotNull(new Script(Test.class, "a", "e", "s", "r"))), //59 dynamicTest("3", () -> assertThrows(expected, () -> new Script(null, "a", "e", "s", "r"))), //60 dynamicTest("4", () -> assertThrows(expected, () -> new Script(Test.class, null, "e", "s", "r"))), //61 dynamicTest("5", () -> assertThrows(expected, () -> new Script(Test.class, "a", null, "s", "r"))), //62 dynamicTest("6", () -> assertThrows(expected, () -> new Script(Test.class, "a", "e", null, "r"))), //63 dynamicTest("7", () -> assertThrows(expected, () -> new Script(Test.class, "a", "e", "s", null))), //64 // engine and source must not be blank65 dynamicTest("8", () -> assertNotNull(new Script(Test.class, "", "e", "s", ""))), //66 dynamicTest("9", () -> assertThrows(expected, () -> new Script(Test.class, "", "", "s", ""))), //67 dynamicTest("A", () -> assertThrows(expected, () -> new Script(Test.class, "", "e", "", ""))) //68 );69 }70 @Test71 void equalsAndHashCode() {72 Script s = new Script(Deprecated.class, "annotation", "engine", "source", "reason");73 // hit short-cut branches74 assertNotEquals(s, null);75 assertNotEquals(s, new Object());76 // annotationAsString and reason pattern are ignored by Script.equals and .hashCode77 Script t = new Script(Deprecated.class, "a.........", "engine", "source", "r.....");78 assertEquals(s, t);79 assertEquals(s.hashCode(), t.hashCode());80 // now assert differences81 Script u = new Script(Deprecated.class, "annotation", "u.....", "source", "reason");...

Full Screen

Full Screen

Source:ReportingTests.java Github

copy

Full Screen

...9 */10package org.junit.jupiter.engine;11import static java.util.Collections.emptyMap;12import static org.junit.jupiter.api.Assertions.assertEquals;13import static org.junit.jupiter.api.Assertions.assertThrows;14import static org.junit.platform.engine.discovery.DiscoverySelectors.selectClass;15import static org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder.request;16import java.util.HashMap;17import java.util.Map;18import org.junit.jupiter.api.AfterEach;19import org.junit.jupiter.api.BeforeEach;20import org.junit.jupiter.api.Test;21import org.junit.jupiter.api.TestReporter;22import org.junit.platform.commons.util.PreconditionViolationException;23import org.junit.platform.engine.test.event.ExecutionEventRecorder;24import org.junit.platform.launcher.LauncherDiscoveryRequest;25/**26 * @since 5.027 */28class ReportingTests extends AbstractJupiterTestEngineTests {29 @Test30 void reportEntriesArePublished() {31 LauncherDiscoveryRequest request = request().selectors(selectClass(MyReportingTestCase.class)).build();32 ExecutionEventRecorder eventRecorder = executeTests(request);33 assertEquals(2, eventRecorder.getTestStartedCount(), "# tests started");34 assertEquals(2, eventRecorder.getTestSuccessfulCount(), "# tests succeeded");35 assertEquals(0, eventRecorder.getTestFailedCount(), "# tests failed");36 assertEquals(7, eventRecorder.getReportingEntryPublishedCount(), "# report entries published");37 }38 static class MyReportingTestCase {39 @BeforeEach40 void beforeEach(TestReporter reporter) {41 reporter.publishEntry("@BeforeEach");42 }43 @AfterEach44 void afterEach(TestReporter reporter) {45 reporter.publishEntry("@AfterEach");46 }47 @Test48 void succeedingTest(TestReporter reporter) {49 reporter.publishEntry(emptyMap());50 reporter.publishEntry("user name", "dk38");51 reporter.publishEntry("message");52 }53 @Test54 void invalidReportData(TestReporter reporter) {55 // Maps56 Map<String, String> map = new HashMap<>();57 map.put("key", null);58 assertThrows(PreconditionViolationException.class, () -> reporter.publishEntry(map));59 map.clear();60 map.put(null, "value");61 assertThrows(PreconditionViolationException.class, () -> reporter.publishEntry(map));62 assertThrows(PreconditionViolationException.class, () -> reporter.publishEntry((Map<String, String>) null));63 // Key-Value pair64 assertThrows(PreconditionViolationException.class, () -> reporter.publishEntry(null, "bar"));65 assertThrows(PreconditionViolationException.class, () -> reporter.publishEntry("foo", null));66 // Value67 assertThrows(PreconditionViolationException.class, () -> reporter.publishEntry((String) null));68 }69 }70}...

Full Screen

Full Screen

Source:AssertThrows.java Github

copy

Full Screen

...24class AssertThrows {25 private AssertThrows() {26 /* no-op */27 }28 static <T extends Throwable> T assertThrows(Class<T> expectedType, Executable executable) {29 return assertThrows(expectedType, executable, (Object) null);30 }31 static <T extends Throwable> T assertThrows(Class<T> expectedType, Executable executable, String message) {32 return assertThrows(expectedType, executable, (Object) message);33 }34 static <T extends Throwable> T assertThrows(Class<T> expectedType, Executable executable,35 Supplier<String> messageSupplier) {36 return assertThrows(expectedType, executable, (Object) messageSupplier);37 }38 @SuppressWarnings("unchecked")39 private static <T extends Throwable> T assertThrows(Class<T> expectedType, Executable executable,40 Object messageOrSupplier) {41 try {42 executable.execute();43 }44 catch (Throwable actualException) {45 if (expectedType.isInstance(actualException)) {46 return (T) actualException;47 }48 else {49 String message = buildPrefix(nullSafeGet(messageOrSupplier))50 + format(expectedType, actualException.getClass(), "Unexpected exception type thrown");51 throw new AssertionFailedError(message, actualException);52 }53 }...

Full Screen

Full Screen

assertThrows

Using AI Code Generation

copy

Full Screen

1import org.junit.Assert;2public void test() {3 Exception exception = Assert.assertThrows(NumberFormatException.class, () -> {4 Integer.parseInt("1a");5 });6 String expectedMessage = "For input string";7 String actualMessage = exception.getMessage();8 assertTrue(actualMessage.contains(expectedMessage));9}10import static org.hamcrest.MatcherAssert.assertThat;11import static org.hamcrest.Matchers.*;12import org.junit.Test;13public class AssertThatTest {14 public void testAssertThat() {15 String str = "Junit is working fine";16 assertThat(str, containsString("working"));17 }18}

Full Screen

Full Screen

assertThrows

Using AI Code Generation

copy

Full Screen

1import static org.junit.jupiter.api.Assertions.assertThrows;2import static org.junit.jupiter.api.Assertions.assertEquals;3import static org.junit.jupiter.api.Assertions.assertTrue;4import static org.junit.jupiter.api.Assertions.assertFalse;5import static org.junit.jupiter.api.Assertions.assertAll;6import static org.junit.jupiter.api.Assertions.assertArrayEquals;7import static org.junit.jupiter.api.Assertions.assertNull

Full Screen

Full Screen

assertThrows

Using AI Code Generation

copy

Full Screen

1import org.junit.Assert;2import org.junit.Test;3public class TestException {4 public void testException() {5 String str = null;6 Assert.assertThrows(NullPointerException.class, () -> str.length());7 }8}9OK (1 test)10import org.junit.jupiter.api.Assertions;11import org.junit.jupiter.api.Test;12public class TestException {13 public void testException() {14 String str = null;15 Assertions.assertThrows(NullPointerException.class, () -> str.length());16 }17}18OK (1 test)19import org.junit.jupiter.api.Assertions;20import org.junit.jupiter.api.Test;21public class TestException {22 public void testException() {23 String str = null;24 Assertions.assertThrows(NullPointerException.class, () -> str.length());25 }26}27OK (1 test)

Full Screen

Full Screen

assertThrows

Using AI Code Generation

copy

Full Screen

1import static org.junit.Assert.assertThrows;2import org.junit.Test;3import java.io.IOException;4public class ExceptionTest {5 public void testIOException() {6 IOException exception = assertThrows(IOException.class, () -> {7 throw new IOException("exception message");8 });9 assertEquals("exception message", exception.getMessage());10 }11}12 at org.junit.Assert.fail(Assert.java:88)13 at org.junit.Assert.failNotEquals(Assert.java:834)14 at org.junit.Assert.assertEquals(Assert.java:645)15 at org.junit.Assert.assertEquals(Assert.java:631)16 at ExceptionTest.testIOException(ExceptionTest.java:10)17 at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)18 at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)19 at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)20 at java.base/java.lang.reflect.Method.invoke(Method.java:566)21 at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)22 at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)23 at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)24 at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)25 at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)26 at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)27 at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)28 at org.junit.runners.ParentRunner$3.run(ParentRunner.java:331)29 at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)30 at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)31 at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)32 at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)33 at org.junit.runners.ParentRunner.run(ParentRunner.java:413)34 at org.junit.runners.Suite.runChild(Suite.java:128)35 at org.junit.runners.Suite.runChild(Suite.java:27)36 at org.junit.runners.ParentRunner$3.run(ParentRunner.java:331

Full Screen

Full Screen

assertThrows

Using AI Code Generation

copy

Full Screen

1org.junit.Assert.assertThrows(2org.junit.jupiter.api.Assertions.assertThrows(3import java.io.File;4import java.io.IOException;5import org.junit.Assert;6import org.junit.Test;7public class AssertThrowsExample {8 public void testAssertThrows() {9 File file = new File("test.txt");10 Assert.assertThrows(IOException.class, () -> file.createNewFile());11 }12}13at org.junit.Assert.assertEquals(Assert.java:115)14at org.junit.Assert.assertEquals(Assert.java:144)15at org.junit.Assert.assertThrows(Assert.java:794)16at org.junit.Assert.assertThrows(Assert.java:780)17at AssertThrowsExample.testAssertThrows(AssertThrowsExample.java:13)18Related Posts: JUnit AssertThrows() Method Example19JUnit 5 AssertThrows() Method Example20Junit AssertEquals() Method Example21JUnit 5 AssertEquals() Method Example22Junit AssertNotEquals() Method Example23JUnit 5 AssertNotEquals() Method Example24JUnit 5 AssertTrue() Method Example25JUnit 5 AssertFalse() Method Example26JUnit 5 AssertNull() Method Example27JUnit 5 AssertNotNull() Method Example28JUnit 5 AssertArrayEquals() Method Example29JUnit 5 AssertSame() Method Example30JUnit 5 AssertNotSame() Method Example31JUnit 5 AssertInstanceOf() Method Example32JUnit 5 AssertAll() Method Example33JUnit 5 AssertTimeout() Method Example34JUnit 5 AssertTimeoutPreemptively() Method Example35JUnit 5 AssertThrows() Method Example36JUnit 5 AssertAll() Method Example37JUnit 5 AssertTimeout() Method Example38JUnit 5 AssertTimeoutPreemptively() Method Example39JUnit 5 AssertThrows() Method Example40JUnit 5 AssertAll() Method Example

Full Screen

Full Screen

assertThrows

Using AI Code Generation

copy

Full Screen

1import static org.junit.Assert.assertThrows;2import java.io.IOException;3import org.junit.Test;4public class AssertThrowsTest {5 public void assertThrowsTest() {6 Exception exception = assertThrows(IOException.class, () -> {7 throw new IOException("IOException thrown");8 });9 String expectedMessage = "IOException thrown";10 String actualMessage = exception.getMessage();11 assertTrue(actualMessage.contains(expectedMessage));12 }13}

Full Screen

Full Screen

assertThrows

Using AI Code Generation

copy

Full Screen

1import static org.junit.Assert.assertThrows;2public class TestAssertThrows {3 public void testAssertThrows() {4 assertThrows(NullPointerException.class, () -> {5 throw new NullPointerException("a message");6 });7 }8}9OK (1 test)10Using assertThrows() method11assertThrows() method is used to test whether the code under test throws an exception or not. The method accepts two parameters:

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