Best junit code snippet using org.junit.Assert.assertThat
Source:AssertionsWithoutMessageCheck.java
...10import org.junit.jupiter.api.function.Executable;11import static checks.MyAbstractIsEqualTo.isEqualTo;12class AssertionsWithoutMessageCheck {13 void foo() {14 org.assertj.core.api.Assertions.assertThat("").usingComparator(null).as("a").isEqualTo(222); // Compliant15 org.junit.Assert.assertTrue(true); // Noncompliant [[sc=22;ec=32]] {{Add a message to this assertion.}}16 org.junit.Assert.assertTrue("message", true);17 org.junit.Assert.assertTrue(1 > 2); // Noncompliant {{Add a message to this assertion.}}18 org.junit.Assert.assertFalse(false); // Noncompliant19 org.junit.Assert.assertFalse("message", false);20 org.junit.Assert.assertEquals("message", "foo", "bar");21 org.junit.Assert.assertEquals("foo", "bar"); // Noncompliant22 junit.framework.Assert.assertTrue(true); // Noncompliant23 junit.framework.Assert.assertTrue("message", true);24 junit.framework.Assert.assertEquals("message", "foo", "bar");25 junit.framework.Assert.assertEquals("message", "foo", "bar");26 junit.framework.Assert.assertEquals("foo", "bar"); // Noncompliant27 junit.framework.Assert.assertNotNull("foo", "bar");28 junit.framework.Assert.assertNotNull("foo"); // Noncompliant29 org.fest.assertions.Assertions.assertThat(true).isTrue();// Noncompliant {{Add a message to this assertion chain before the predicate method.}}30 org.fest.assertions.Assertions.assertThat(true).as("verifying the truth").isTrue();31 org.fest.assertions.Assertions.assertThat(true).as(new BasicDescription("description")).isTrue();32 org.fest.assertions.Assertions.assertThat(true).describedAs("verifying the truth").isTrue(); // compliant - describedAs is an alias for as33 org.fest.assertions.Assertions.assertThat(true).describedAs(new BasicDescription("description"));34 org.fest.assertions.Assertions.assertThat(true).overridingErrorMessage("error message").isTrue();35 org.fest.assertions.Assertions.assertThat("").as("Message").isEqualTo("");36 org.fest.assertions.Assertions.assertThat("").isEqualTo("").as("Message"); // Noncompliant37 org.assertj.core.api.Assertions.assertThat(true).isTrue(); // Noncompliant38 org.assertj.core.api.Assertions.assertThatObject(true).isEqualTo(""); // Noncompliant39 org.assertj.core.api.Assertions.assertThat(true).as("verifying the truth").isTrue();40 org.assertj.core.api.Assertions.assertThat(true).as("verifying the truth", new Object()).isTrue();41 org.assertj.core.api.Assertions.assertThat(true).as(new TextDescription("verifying the truth")).isTrue();42 org.assertj.core.api.Assertions.assertThat(true).describedAs("verifying the truth").isTrue(); // compliant - describedAs is an alias for as43 org.assertj.core.api.Assertions.assertThat(true).describedAs("verifying the truth", new Object()).isTrue();44 org.assertj.core.api.Assertions.assertThat(true).describedAs(new TextDescription("verifying the truth")).isTrue();45 org.assertj.core.api.Assertions.assertThat(true).withFailMessage("fail message").isTrue();46 org.assertj.core.api.Assertions.assertThat(true).withFailMessage("fail message", new Object()).isTrue();47 org.assertj.core.api.Assertions.assertThat(true).overridingErrorMessage("fail message").isTrue();48 org.assertj.core.api.Assertions.assertThat(true).overridingErrorMessage("fail message", new Object()).isTrue();49 org.assertj.core.api.Assertions.assertThat("").as("Message").isEqualTo("");50 org.assertj.core.api.Assertions.assertThat("").isEqualTo("").as("Message"); // Noncompliant [[sc=52;ec=61]] {{Add a message to this assertion chain before the predicate method.}}51 org.assertj.core.api.Assertions.assertThat("").matches("x").matches("y"); // Noncompliant [[sc=52;ec=59]]52 org.assertj.core.api.AssertionsForClassTypes.assertThat("").isEqualTo(""); // Noncompliant53 org.assertj.core.api.Assertions.assertThat("").usingComparator(null).as("a").isEqualTo(222); // Compliant54 org.assertj.core.api.Assertions.assertThat("").as("message").usingComparator(null).isEqualTo(222); // Compliant55 org.assertj.core.api.Assertions.assertThat("").isEqualTo("1").usingComparator(null).isEqualTo("2"); // Noncompliant [[sc=52;ec=61]]56 org.assertj.core.api.Assertions.assertThat("").usingComparator(null).isEqualTo(222); // Noncompliant57 org.assertj.core.api.Assertions.assertThat(new Object()).as("message").extracting("field").isEqualTo(222); // Compliant58 org.assertj.core.api.Assertions.assertThat(new Object()).extracting("field").isEqualTo(222); // Noncompliant59 org.assertj.core.api.Assertions.assertThat(new ArrayList<>()).as("message").filteredOn("s", "e").isEqualTo(222); // Compliant60 org.assertj.core.api.Assertions.assertThat(new ArrayList<>()).filteredOn("s", "e").isEqualTo(222); // Noncompliant61 AbstractStringAssert variableAssert = org.assertj.core.api.Assertions.assertThat("").as("message");62 variableAssert.isEqualTo(""); // Compliant63 AbstractStringAssert variableAssertWithoutMessage = org.assertj.core.api.Assertions.assertThat("");64 variableAssertWithoutMessage.isEqualTo(""); // FN, we can not be sure that the assertion provide a message65 // Compliant, not used as expected (for coverage)66 isEqualTo();67 MyAbstractIsEqualTo.isEqualTo();68 org.junit.Assert.assertThat("foo", null); // Noncompliant {{Add a message to this assertion.}}69 org.junit.Assert.assertThat("foo", "bar", null);70 org.junit.Assert.assertThat("foo", new Integer(1), null);71 junit.framework.Assert.assertNotSame("foo", "bar"); // Noncompliant72 junit.framework.Assert.assertNotSame("foo", "foo", "bar");73 junit.framework.Assert.assertSame("foo", "bar"); // Noncompliant74 junit.framework.Assert.assertSame("foo", "foo", "bar");75 org.junit.Assert.fail(); // Noncompliant76 org.junit.Assert.fail("Foo");77 junit.framework.Assert.fail(); // Noncompliant78 junit.framework.Assert.fail("Foo");79 org.fest.assertions.Fail.fail(); // Noncompliant80 org.fest.assertions.Fail.fail("foo");81 org.fest.assertions.Fail.fail("foo", null);82 org.fest.assertions.Fail.failure("foo");83 }84 void junit5() {...
Source:DiscoveryRequestCreatorTests.java
...10package org.junit.platform.console.tasks;11import static java.util.Arrays.asList;12import static java.util.Collections.singletonList;13import static java.util.stream.Collectors.toMap;14import static org.assertj.core.api.Assertions.assertThat;15import static org.assertj.core.api.Assertions.entry;16import static org.junit.jupiter.api.Assertions.assertThrows;17import static org.junit.platform.engine.discovery.ClassNameFilter.STANDARD_INCLUDE_PATTERN;18import java.io.File;19import java.net.URI;20import java.nio.file.Paths;21import java.util.List;22import java.util.Map;23import java.util.Map.Entry;24import java.util.stream.Stream;25import org.junit.jupiter.api.Test;26import org.junit.platform.commons.util.PreconditionViolationException;27import org.junit.platform.console.options.CommandLineOptions;28import org.junit.platform.engine.ConfigurationParameters;29import org.junit.platform.engine.discovery.ClassNameFilter;30import org.junit.platform.engine.discovery.ClassSelector;31import org.junit.platform.engine.discovery.ClasspathResourceSelector;32import org.junit.platform.engine.discovery.ClasspathRootSelector;33import org.junit.platform.engine.discovery.DirectorySelector;34import org.junit.platform.engine.discovery.FileSelector;35import org.junit.platform.engine.discovery.MethodSelector;36import org.junit.platform.engine.discovery.PackageNameFilter;37import org.junit.platform.engine.discovery.PackageSelector;38import org.junit.platform.engine.discovery.UriSelector;39import org.junit.platform.launcher.EngineFilter;40import org.junit.platform.launcher.LauncherDiscoveryRequest;41import org.junit.platform.launcher.PostDiscoveryFilter;42/**43 * @since 1.044 */45class DiscoveryRequestCreatorTests {46 private final CommandLineOptions options = new CommandLineOptions();47 @Test48 void convertsScanClasspathOptionWithoutExplicitRootDirectories() {49 options.setScanClasspath(true);50 LauncherDiscoveryRequest request = convert();51 List<ClasspathRootSelector> classpathRootSelectors = request.getSelectorsByType(ClasspathRootSelector.class);52 // @formatter:off53 assertThat(classpathRootSelectors).extracting(ClasspathRootSelector::getClasspathRoot)54 .hasAtLeastOneElementOfType(URI.class)55 .doesNotContainNull();56 // @formatter:on57 }58 @Test59 void convertsScanClasspathOptionWithExplicitRootDirectories() {60 options.setScanClasspath(true);61 options.setSelectedClasspathEntries(asList(Paths.get("."), Paths.get("..")));62 LauncherDiscoveryRequest request = convert();63 List<ClasspathRootSelector> classpathRootSelectors = request.getSelectorsByType(ClasspathRootSelector.class);64 // @formatter:off65 assertThat(classpathRootSelectors).extracting(ClasspathRootSelector::getClasspathRoot)66 .containsExactly(new File(".").toURI(), new File("..").toURI());67 // @formatter:on68 }69 @Test70 void convertsScanClasspathOptionWithAdditionalClasspathEntries() {71 options.setScanClasspath(true);72 options.setAdditionalClasspathEntries(asList(Paths.get("."), Paths.get("..")));73 LauncherDiscoveryRequest request = convert();74 List<ClasspathRootSelector> classpathRootSelectors = request.getSelectorsByType(ClasspathRootSelector.class);75 // @formatter:off76 assertThat(classpathRootSelectors).extracting(ClasspathRootSelector::getClasspathRoot)77 .contains(new File(".").toURI(), new File("..").toURI());78 // @formatter:on79 }80 @Test81 void doesNotSupportScanClasspathAndExplicitSelectors() {82 options.setScanClasspath(true);83 options.setSelectedClasses(singletonList("SomeTest"));84 Throwable cause = assertThrows(PreconditionViolationException.class, this::convert);85 assertThat(cause).hasMessageContaining("not supported");86 }87 @Test88 void convertsDefaultIncludeClassNamePatternOption() {89 options.setScanClasspath(true);90 LauncherDiscoveryRequest request = convert();91 List<ClassNameFilter> filter = request.getFiltersByType(ClassNameFilter.class);92 assertThat(filter).hasSize(1);93 assertThat(filter.get(0).toString()).contains(STANDARD_INCLUDE_PATTERN);94 }95 @Test96 void convertsExplicitIncludeClassNamePatternOption() {97 options.setScanClasspath(true);98 options.setIncludedClassNamePatterns(asList("Foo.*Bar", "Bar.*Foo"));99 LauncherDiscoveryRequest request = convert();100 List<ClassNameFilter> filter = request.getFiltersByType(ClassNameFilter.class);101 assertThat(filter).hasSize(1);102 assertThat(filter.get(0).toString()).contains("Foo.*Bar");103 assertThat(filter.get(0).toString()).contains("Bar.*Foo");104 }105 @Test106 void convertsExcludeClassNamePatternOption() {107 options.setScanClasspath(true);108 options.setExcludedClassNamePatterns(asList("Foo.*Bar", "Bar.*Foo"));109 LauncherDiscoveryRequest request = convert();110 List<ClassNameFilter> filter = request.getFiltersByType(ClassNameFilter.class);111 assertThat(filter).hasSize(2);112 assertThat(filter.get(1).toString()).contains("Foo.*Bar");113 assertThat(filter.get(1).toString()).contains("Bar.*Foo");114 }115 @Test116 void convertsPackageOptions() {117 options.setScanClasspath(true);118 options.setIncludedPackages(asList("org.junit.included1", "org.junit.included2", "org.junit.included3"));119 options.setExcludedPackages(asList("org.junit.excluded1"));120 LauncherDiscoveryRequest request = convert();121 List<PackageNameFilter> packageNameFilters = request.getFiltersByType(PackageNameFilter.class);122 assertThat(packageNameFilters).hasSize(2);123 assertThat(packageNameFilters.get(0).toString()).contains("org.junit.included1");124 assertThat(packageNameFilters.get(0).toString()).contains("org.junit.included2");125 assertThat(packageNameFilters.get(0).toString()).contains("org.junit.included3");126 assertThat(packageNameFilters.get(1).toString()).contains("org.junit.excluded1");127 }128 @Test129 void convertsTagOptions() {130 options.setScanClasspath(true);131 options.setIncludedTagExpressions(asList("fast", "medium", "slow"));132 options.setExcludedTagExpressions(asList("slow"));133 LauncherDiscoveryRequest request = convert();134 List<PostDiscoveryFilter> postDiscoveryFilters = request.getPostDiscoveryFilters();135 assertThat(postDiscoveryFilters).hasSize(2);136 assertThat(postDiscoveryFilters.get(0).toString()).contains("TagFilter");137 assertThat(postDiscoveryFilters.get(1).toString()).contains("TagFilter");138 }139 @Test140 void convertsEngineOptions() {141 options.setScanClasspath(true);142 options.setIncludedEngines(asList("engine1", "engine2", "engine3"));143 options.setExcludedEngines(singletonList("engine2"));144 LauncherDiscoveryRequest request = convert();145 List<EngineFilter> engineFilters = request.getEngineFilters();146 assertThat(engineFilters).hasSize(2);147 assertThat(engineFilters.get(0).toString()).contains("includes", "[engine1, engine2, engine3]");148 assertThat(engineFilters.get(1).toString()).contains("excludes", "[engine2]");149 }150 @Test151 void convertsUriSelectors() {152 options.setSelectedUris(asList(URI.create("a"), URI.create("b")));153 LauncherDiscoveryRequest request = convert();154 List<UriSelector> uriSelectors = request.getSelectorsByType(UriSelector.class);155 assertThat(uriSelectors).extracting(UriSelector::getUri).containsExactly(URI.create("a"), URI.create("b"));156 }157 @Test158 void convertsFileSelectors() {159 options.setSelectedFiles(asList("foo.txt", "bar.csv"));160 LauncherDiscoveryRequest request = convert();161 List<FileSelector> fileSelectors = request.getSelectorsByType(FileSelector.class);162 assertThat(fileSelectors).extracting(FileSelector::getRawPath).containsExactly("foo.txt", "bar.csv");163 }164 @Test165 void convertsDirectorySelectors() {166 options.setSelectedDirectories(asList("foo/bar", "bar/qux"));167 LauncherDiscoveryRequest request = convert();168 List<DirectorySelector> directorySelectors = request.getSelectorsByType(DirectorySelector.class);169 assertThat(directorySelectors).extracting(DirectorySelector::getRawPath).containsExactly("foo/bar", "bar/qux");170 }171 @Test172 void convertsPackageSelectors() {173 options.setSelectedPackages(asList("com.acme.foo", "com.example.bar"));174 LauncherDiscoveryRequest request = convert();175 List<PackageSelector> packageSelectors = request.getSelectorsByType(PackageSelector.class);176 assertThat(packageSelectors).extracting(PackageSelector::getPackageName).containsExactly("com.acme.foo",177 "com.example.bar");178 }179 @Test180 void convertsClassSelectors() {181 options.setSelectedClasses(asList("com.acme.Foo", "com.example.Bar"));182 LauncherDiscoveryRequest request = convert();183 List<ClassSelector> classSelectors = request.getSelectorsByType(ClassSelector.class);184 assertThat(classSelectors).extracting(ClassSelector::getClassName).containsExactly("com.acme.Foo",185 "com.example.Bar");186 }187 @Test188 void convertsMethodSelectors() {189 options.setSelectedMethods(asList("com.acme.Foo#m()", "com.example.Bar#method(java.lang.Object)"));190 LauncherDiscoveryRequest request = convert();191 List<MethodSelector> methodSelectors = request.getSelectorsByType(MethodSelector.class);192 assertThat(methodSelectors).hasSize(2);193 assertThat(methodSelectors.get(0).getClassName()).isEqualTo("com.acme.Foo");194 assertThat(methodSelectors.get(0).getMethodName()).isEqualTo("m");195 assertThat(methodSelectors.get(0).getMethodParameterTypes()).isEqualTo("");196 assertThat(methodSelectors.get(1).getClassName()).isEqualTo("com.example.Bar");197 assertThat(methodSelectors.get(1).getMethodName()).isEqualTo("method");198 assertThat(methodSelectors.get(1).getMethodParameterTypes()).isEqualTo("java.lang.Object");199 }200 @Test201 void convertsClasspathResourceSelectors() {202 options.setSelectedClasspathResources(asList("foo.csv", "com/example/bar.json"));203 LauncherDiscoveryRequest request = convert();204 List<ClasspathResourceSelector> classpathResourceSelectors = request.getSelectorsByType(205 ClasspathResourceSelector.class);206 assertThat(classpathResourceSelectors).extracting(207 ClasspathResourceSelector::getClasspathResourceName).containsExactly("foo.csv", "com/example/bar.json");208 }209 @Test210 void convertsConfigurationParameters() {211 options.setScanClasspath(true);212 options.setConfigurationParameters(mapOf(entry("foo", "bar"), entry("baz", "true")));213 LauncherDiscoveryRequest request = convert();214 ConfigurationParameters configurationParameters = request.getConfigurationParameters();215 assertThat(configurationParameters.size()).isEqualTo(2);216 assertThat(configurationParameters.get("foo")).contains("bar");217 assertThat(configurationParameters.getBoolean("baz")).contains(true);218 }219 private LauncherDiscoveryRequest convert() {220 DiscoveryRequestCreator creator = new DiscoveryRequestCreator();221 return creator.toDiscoveryRequest(options);222 }223 @SafeVarargs224 @SuppressWarnings("varargs")225 private static <K, V> Map<K, V> mapOf(Entry<K, V>... entries) {226 return Stream.of(entries).collect(toMap(Entry::getKey, Entry::getValue));227 }228}...
Source:TestWatcherTest.java
1package org.junit.tests.experimental.rules;2import static junit.framework.Assert.fail;3import static org.hamcrest.CoreMatchers.is;4import static org.junit.Assert.assertThat;5import static org.junit.Assume.assumeTrue;6import static org.junit.experimental.results.PrintableResult.testResult;7import static org.junit.experimental.results.ResultMatchers.failureCountIs;8import static org.junit.experimental.results.ResultMatchers.hasFailureContaining;9import static org.junit.runner.JUnitCore.runClasses;10import org.junit.Rule;11import org.junit.Test;12import org.junit.experimental.results.PrintableResult;13import org.junit.internal.AssumptionViolatedException;14import org.junit.rules.TestRule;15import org.junit.rules.TestWatcher;16import org.junit.runner.Description;17public class TestWatcherTest {18 public static class ViolatedAssumptionTest {19 private static StringBuilder watchedLog = new StringBuilder();20 @Rule21 public TestRule watcher = new LoggingTestWatcher(watchedLog);22 @Test23 public void succeeds() {24 assumeTrue(false);25 }26 }27 @Test28 public void neitherLogSuccessNorFailedForViolatedAssumption() {29 ViolatedAssumptionTest.watchedLog = new StringBuilder();30 runClasses(ViolatedAssumptionTest.class);31 assertThat(ViolatedAssumptionTest.watchedLog.toString(),32 is("starting finished "));33 }34 public static class TestWatcherSkippedThrowsExceptionTest {35 @Rule36 public TestRule watcher = new TestWatcher() {37 @Override38 protected void skipped(AssumptionViolatedException e, Description description) {39 throw new RuntimeException("watcher failure");40 }41 };42 @Test43 public void fails() {44 throw new AssumptionViolatedException("test failure");45 }46 }47 @Test48 public void testWatcherSkippedThrowsException() {49 PrintableResult result = testResult(TestWatcherSkippedThrowsExceptionTest.class);50 assertThat(result, failureCountIs(2));51 assertThat(result, hasFailureContaining("test failure"));52 assertThat(result, hasFailureContaining("watcher failure"));53 }54 public static class FailingTest {55 private static StringBuilder watchedLog = new StringBuilder();56 @Rule57 public TestRule watcher = new LoggingTestWatcher(watchedLog);58 @Test59 public void succeeds() {60 fail();61 }62 }63 @Test64 public void logFailingTest() {65 FailingTest.watchedLog = new StringBuilder();66 runClasses(FailingTest.class);67 assertThat(FailingTest.watchedLog.toString(),68 is("starting failed finished "));69 }70 public static class TestWatcherFailedThrowsExceptionTest {71 @Rule72 public TestRule watcher = new TestWatcher() {73 @Override74 protected void failed(Throwable e, Description description) {75 throw new RuntimeException("watcher failure");76 }77 };78 @Test79 public void fails() {80 throw new IllegalArgumentException("test failure");81 }82 }83 @Test84 public void testWatcherFailedThrowsException() {85 PrintableResult result = testResult(TestWatcherFailedThrowsExceptionTest.class);86 assertThat(result, failureCountIs(2));87 assertThat(result, hasFailureContaining("test failure"));88 assertThat(result, hasFailureContaining("watcher failure"));89 }90 public static class TestWatcherStartingThrowsExceptionTest {91 @Rule92 public TestRule watcher = new TestWatcher() {93 @Override94 protected void starting(Description description) {95 throw new RuntimeException("watcher failure");96 }97 };98 @Test99 public void fails() {100 throw new IllegalArgumentException("test failure");101 }102 }103 @Test104 public void testWatcherStartingThrowsException() {105 PrintableResult result = testResult(TestWatcherStartingThrowsExceptionTest.class);106 assertThat(result, failureCountIs(2));107 assertThat(result, hasFailureContaining("test failure"));108 assertThat(result, hasFailureContaining("watcher failure"));109 }110 public static class TestWatcherFailedAndFinishedThrowsExceptionTest {111 @Rule112 public TestRule watcher = new TestWatcher() {113 @Override114 protected void failed(Throwable t, Description description) {115 throw new RuntimeException("watcher failed failure");116 }117 @Override118 protected void finished(Description description) {119 throw new RuntimeException("watcher finished failure");120 }121 };122 @Test123 public void fails() {124 throw new IllegalArgumentException("test failure");125 }126 }127 @Test128 public void testWatcherFailedAndFinishedThrowsException() {129 PrintableResult result = testResult(TestWatcherFailedAndFinishedThrowsExceptionTest.class);130 assertThat(result, failureCountIs(3));131 assertThat(result, hasFailureContaining("test failure"));132 assertThat(result, hasFailureContaining("watcher failed failure"));133 assertThat(result, hasFailureContaining("watcher finished failure"));134 }135}...
Source:StopwatchTest.java
...9import org.junit.runner.Result;10import static java.util.concurrent.TimeUnit.MILLISECONDS;11import static org.hamcrest.core.Is.is;12import static org.junit.Assert.assertEquals;13import static org.junit.Assert.assertThat;14import static org.junit.Assume.assumeTrue;15import static org.junit.Assert.assertTrue;16import static org.junit.Assert.fail;17import static org.junit.Assert.assertNotEquals;18/**19 * @author tibor1720 * @since 4.1221 */22public class StopwatchTest {23 private static enum TestStatus { SUCCEEDED, FAILED, SKIPPED }24 private static Record fRecord;25 private static Record fFinishedRecord;26 private static class Record {27 final long fDuration;28 final String fName;29 final TestStatus fStatus;30 Record() {31 this(0, null, null);32 }33 Record(long duration, String name) {34 this(duration, null, name);35 }36 Record(long duration, TestStatus status, String name) {37 fDuration= duration;38 fStatus= status;39 fName= name;40 }41 }42 public static abstract class AbstractStopwatchTest {43 @Rule44 public final Stopwatch fStopwatch= new Stopwatch() {45 @Override46 protected void succeeded(long nanos, Description description) {47 StopwatchTest.fRecord= new Record(nanos, TestStatus.SUCCEEDED, description.getMethodName());48 }49 @Override50 protected void failed(long nanos, Throwable e, Description description) {51 StopwatchTest.fRecord= new Record(nanos, TestStatus.FAILED, description.getMethodName());52 }53 @Override54 protected void skipped(long nanos, AssumptionViolatedException e, Description description) {55 StopwatchTest.fRecord= new Record(nanos, TestStatus.SKIPPED, description.getMethodName());56 }57 @Override58 protected void finished(long nanos, Description description) {59 StopwatchTest.fFinishedRecord= new Record(nanos, description.getMethodName());60 }61 };62 }63 public static class SuccessfulTest extends AbstractStopwatchTest {64 @Test65 public void successfulTest() {66 }67 }68 public static class FailedTest extends AbstractStopwatchTest {69 @Test70 public void failedTest() {71 fail();72 }73 }74 public static class SkippedTest extends AbstractStopwatchTest {75 @Test76 public void skippedTest() {77 assumeTrue(false);78 }79 }80 public static class WrongDurationTest extends AbstractStopwatchTest {81 @Test82 public void wrongDuration() throws InterruptedException {83 Thread.sleep(500L);84 assertNotEquals(fStopwatch.runtime(MILLISECONDS), 300d, 100d);85 }86 }87 public static class DurationTest extends AbstractStopwatchTest {88 @Test89 public void duration() throws InterruptedException {90 Thread.sleep(300L);91 assertEquals(300d, fStopwatch.runtime(MILLISECONDS), 100d);92 Thread.sleep(500L);93 assertEquals(800d, fStopwatch.runtime(MILLISECONDS), 250d);94 }95 }96 @Before97 public void init() {98 fRecord= new Record();99 fFinishedRecord= new Record();100 }101 @Test102 public void succeeded() {103 Result result= JUnitCore.runClasses(SuccessfulTest.class);104 assertEquals(0, result.getFailureCount());105 assertThat(fRecord.fName, is("successfulTest"));106 assertThat(fRecord.fName, is(fFinishedRecord.fName));107 assertThat(fRecord.fStatus, is(TestStatus.SUCCEEDED));108 assertTrue("timeSpent > 0", fRecord.fDuration > 0);109 assertThat(fRecord.fDuration, is(fFinishedRecord.fDuration));110 }111 @Test112 public void failed() {113 Result result= JUnitCore.runClasses(FailedTest.class);114 assertEquals(1, result.getFailureCount());115 assertThat(fRecord.fName, is("failedTest"));116 assertThat(fRecord.fName, is(fFinishedRecord.fName));117 assertThat(fRecord.fStatus, is(TestStatus.FAILED));118 assertTrue("timeSpent > 0", fRecord.fDuration > 0);119 assertThat(fRecord.fDuration, is(fFinishedRecord.fDuration));120 }121 @Test122 public void skipped() {123 Result result= JUnitCore.runClasses(SkippedTest.class);124 assertEquals(0, result.getFailureCount());125 assertThat(fRecord.fName, is("skippedTest"));126 assertThat(fRecord.fName, is(fFinishedRecord.fName));127 assertThat(fRecord.fStatus, is(TestStatus.SKIPPED));128 assertTrue("timeSpent > 0", fRecord.fDuration > 0);129 assertThat(fRecord.fDuration, is(fFinishedRecord.fDuration));130 }131 @Test132 public void wrongDuration() {133 Result result= JUnitCore.runClasses(WrongDurationTest.class);134 assertTrue(result.wasSuccessful());135 }136 @Test137 public void duration() {138 Result result= JUnitCore.runClasses(DurationTest.class);139 assertTrue(result.wasSuccessful());140 }141}...
Source:VerifierRuleTest.java
1package org.junit.tests.experimental.rules;2import static org.hamcrest.CoreMatchers.is;3import static org.junit.Assert.assertEquals;4import static org.junit.Assert.assertThat;5import static org.junit.experimental.results.PrintableResult.testResult;6import static org.junit.experimental.results.ResultMatchers.hasFailureContaining;7import static org.junit.experimental.results.ResultMatchers.isSuccessful;8import java.util.concurrent.Callable;9import org.junit.Rule;10import org.junit.Test;11import org.junit.experimental.results.PrintableResult;12import org.junit.rules.ErrorCollector;13import org.junit.rules.Verifier;14public class VerifierRuleTest {15 public static class UsesErrorCollector {16 @Rule17 public ErrorCollector collector = new ErrorCollector();18 @Test19 public void example() {20 collector.addError(new Throwable("message"));21 }22 }23 @Test24 public void usedErrorCollectorShouldFail() {25 assertThat(testResult(UsesErrorCollector.class), hasFailureContaining("message"));26 }27 public static class UsesErrorCollectorTwice {28 @Rule29 public ErrorCollector collector = new ErrorCollector();30 @Test31 public void example() {32 collector.addError(new Throwable("first thing went wrong"));33 collector.addError(new Throwable("second thing went wrong"));34 }35 }36 @Test37 public void usedErrorCollectorTwiceShouldFail() {38 PrintableResult testResult = testResult(UsesErrorCollectorTwice.class);39 assertThat(testResult, hasFailureContaining("first thing went wrong"));40 assertThat(testResult, hasFailureContaining("second thing went wrong"));41 }42 public static class UsesErrorCollectorCheckThat {43 @Rule44 public ErrorCollector collector = new ErrorCollector();45 @Test46 public void example() {47 collector.checkThat(3, is(4));48 collector.checkThat(5, is(6));49 collector.checkThat("reason 1", 7, is(8));50 collector.checkThat("reason 2", 9, is(16));51 }52 }53 @Test54 public void usedErrorCollectorCheckThatShouldFail() {55 PrintableResult testResult = testResult(UsesErrorCollectorCheckThat.class);56 assertThat(testResult, hasFailureContaining("was <3>"));57 assertThat(testResult, hasFailureContaining("was <5>"));58 assertThat(testResult, hasFailureContaining("reason 1"));59 assertThat(testResult, hasFailureContaining("was <7>"));60 assertThat(testResult, hasFailureContaining("reason 2"));61 assertThat(testResult, hasFailureContaining("was <9>"));62 }63 public static class UsesErrorCollectorCheckSucceeds {64 @Rule65 public ErrorCollector collector = new ErrorCollector();66 @Test67 public void example() {68 collector.checkSucceeds(new Callable<Object>() {69 public Object call() throws Exception {70 throw new RuntimeException("first!");71 }72 });73 collector.checkSucceeds(new Callable<Object>() {74 public Object call() throws Exception {75 throw new RuntimeException("second!");76 }77 });78 }79 }80 @Test81 public void usedErrorCollectorCheckSucceedsShouldFail() {82 PrintableResult testResult = testResult(UsesErrorCollectorCheckSucceeds.class);83 assertThat(testResult, hasFailureContaining("first!"));84 assertThat(testResult, hasFailureContaining("second!"));85 }86 public static class UsesErrorCollectorCheckSucceedsPasses {87 @Rule88 public ErrorCollector collector = new ErrorCollector();89 @Test90 public void example() {91 assertEquals(3, collector.checkSucceeds(new Callable<Object>() {92 public Object call() throws Exception {93 return 3;94 }95 }));96 }97 }98 @Test99 public void usedErrorCollectorCheckSucceedsShouldPass() {100 PrintableResult testResult = testResult(UsesErrorCollectorCheckSucceedsPasses.class);101 assertThat(testResult, isSuccessful());102 }103 private static String sequence;104 public static class UsesVerifier {105 @Rule106 public Verifier collector = new Verifier() {107 @Override108 protected void verify() {109 sequence += "verify ";110 }111 };112 @Test113 public void example() {114 sequence += "test ";115 }116 }117 @Test118 public void verifierRunsAfterTest() {119 sequence = "";120 assertThat(testResult(UsesVerifier.class), isSuccessful());121 assertEquals("test verify ", sequence);122 }123}...
Source:AssumptionTest.java
1package org.junit.tests.experimental;23import static org.hamcrest.CoreMatchers.is;4import static org.junit.Assert.assertThat;5import static org.junit.Assert.fail;6import static org.junit.Assume.assumeNoException;7import static org.junit.Assume.assumeNotNull;8import static org.junit.Assume.assumeThat;9import static org.junit.Assume.assumeTrue;10import static org.junit.experimental.results.PrintableResult.testResult;11import static org.junit.experimental.results.ResultMatchers.isSuccessful;12import static org.junit.internal.matchers.StringContains.containsString;13import org.junit.Assume;14import org.junit.Before;15import org.junit.BeforeClass;16import org.junit.Test;17import org.junit.internal.AssumptionViolatedException;18import org.junit.runner.JUnitCore;19import org.junit.runner.Result;20import org.junit.runner.notification.Failure;21import org.junit.runner.notification.RunListener;2223public class AssumptionTest {24 public static class HasFailingAssumption {25 @Test26 public void assumptionsFail() {27 assumeThat(3, is(4));28 fail();29 }30 }3132 @Test33 public void failedAssumptionsMeanPassing() {34 Result result= JUnitCore.runClasses(HasFailingAssumption.class);35 assertThat(result.getRunCount(), is(1));36 assertThat(result.getIgnoreCount(), is(0));37 assertThat(result.getFailureCount(), is(0));38 }3940 private static int assumptionFailures= 0;41 @Test42 public void failedAssumptionsCanBeDetectedByListeners() {43 assumptionFailures= 0;44 JUnitCore core= new JUnitCore();45 core.addListener(new RunListener() {46 @Override47 public void testAssumptionFailure(Failure failure) {48 assumptionFailures++;49 }50 });51 core.run(HasFailingAssumption.class);52 53 assertThat(assumptionFailures, is(1));54 }5556 public static class HasPassingAssumption {57 @Test58 public void assumptionsFail() {59 assumeThat(3, is(3));60 fail();61 }62 }6364 @Test65 public void passingAssumptionsScootThrough() {66 Result result= JUnitCore.runClasses(HasPassingAssumption.class);67 assertThat(result.getRunCount(), is(1));68 assertThat(result.getIgnoreCount(), is(0));69 assertThat(result.getFailureCount(), is(1));70 }7172 @Test(expected= AssumptionViolatedException.class)73 public void assumeThatWorks() {74 assumeThat(1, is(2));75 }7677 @Test78 public void assumeThatPasses() {79 assumeThat(1, is(1));80 assertCompletesNormally();81 }8283 @Test84 public void assumeThatPassesOnStrings() {85 assumeThat("x", is("x"));86 assertCompletesNormally();87 }8889 @Test(expected= AssumptionViolatedException.class)90 public void assumeNotNullThrowsException() {91 Object[] objects= { 1, 2, null };92 assumeNotNull(objects);93 }9495 @Test96 public void assumeNotNullPasses() {97 Object[] objects= { 1, 2 };98 assumeNotNull(objects);99 assertCompletesNormally();100 }101102 @Test103 public void assumeNotNullIncludesParameterList() {104 try {105 Object[] objects= { 1, 2, null };106 assumeNotNull(objects);107 } catch (AssumptionViolatedException e) {108 assertThat(e.getMessage(), containsString("1, 2, null"));109 } catch (Exception e) {110 fail("Should have thrown AssumptionViolatedException");111 }112 }113 @Test114 public void assumeNoExceptionThrows() {115 final Throwable exception= new NullPointerException();116 try {117 assumeNoException(exception);118 fail("Should have thrown exception");119 } catch (AssumptionViolatedException e) {120 assertThat(e.getCause(), is(exception));121 }122 }123124 private void assertCompletesNormally() {125 }126127 @Test(expected=AssumptionViolatedException.class) public void assumeTrueWorks() {128 Assume.assumeTrue(false);129 }130131 public static class HasFailingAssumeInBefore {132 @Before public void checkForSomethingThatIsntThere() {133 assumeTrue(false);134 }135136 @Test public void failing() {137 fail();138 }139 }140141 @Test public void failingAssumptionInBeforePreventsTestRun() {142 assertThat(testResult(HasFailingAssumeInBefore.class), isSuccessful());143 }144145 public static class HasFailingAssumeInBeforeClass {146 @BeforeClass public static void checkForSomethingThatIsntThere() {147 assumeTrue(false);148 }149150 @Test public void failing() {151 fail();152 }153 }154155 @Test public void failingAssumptionInBeforeClassIgnoresClass() {156 assertThat(testResult(HasFailingAssumeInBeforeClass.class), isSuccessful());157 }158159 public static class AssumptionFailureInConstructor {160 public AssumptionFailureInConstructor() {161 assumeTrue(false);162 }163164 @Test public void shouldFail() {165 fail();166 }167 }168169 @Test public void failingAssumptionInConstructorIgnoresClass() {170 assertThat(testResult(AssumptionFailureInConstructor.class), isSuccessful());171 }172}
...
Source:TagExpressionsTests.java
...7 *8 * https://www.eclipse.org/legal/epl-v20.html9 */10package org.junit.platform.launcher.tagexpression;11import static org.assertj.core.api.Assertions.assertThat;12import static org.junit.jupiter.api.Assertions.assertThrows;13import static org.junit.platform.engine.TestTag.create;14import static org.junit.platform.launcher.tagexpression.TagExpressions.and;15import static org.junit.platform.launcher.tagexpression.TagExpressions.any;16import static org.junit.platform.launcher.tagexpression.TagExpressions.none;17import static org.junit.platform.launcher.tagexpression.TagExpressions.not;18import static org.junit.platform.launcher.tagexpression.TagExpressions.or;19import static org.junit.platform.launcher.tagexpression.TagExpressions.tag;20import java.util.Set;21import org.junit.jupiter.api.Test;22import org.junit.platform.commons.PreconditionViolationException;23import org.junit.platform.engine.TestTag;24class TagExpressionsTests {25 private static final TagExpression True = tags -> true;26 private static final TagExpression False = tags -> false;27 @Test28 void tagIsJustATestTag() {29 assertThat(tag("foo")).hasToString("foo");30 }31 @Test32 void rejectInvalidTestTags() {33 RuntimeException expected = assertThrows(PreconditionViolationException.class,34 () -> tag("tags with spaces are not allowed"));35 assertThat(expected).hasMessageContaining("tags with spaces are not allowed");36 }37 @Test38 void tagEvaluation() {39 var tagExpression = tag("foo");40 assertThat(tagExpression.evaluate(Set.of(create("foo")))).isTrue();41 assertThat(tagExpression.evaluate(Set.of(create("not_foo")))).isFalse();42 }43 @Test44 void justConcatenateNot() {45 assertThat(not(tag("foo"))).hasToString("!foo");46 assertThat(not(and(tag("foo"), tag("bar")))).hasToString("!(foo & bar)");47 assertThat(not(or(tag("foo"), tag("bar")))).hasToString("!(foo | bar)");48 }49 @Test50 void notEvaluation() {51 assertThat(not(True).evaluate(Set.of())).isFalse();52 assertThat(not(False).evaluate(Set.of())).isTrue();53 }54 @Test55 void encloseAndWithParenthesis() {56 assertThat(and(tag("foo"), tag("bar"))).hasToString("(foo & bar)");57 }58 @Test59 void andEvaluation() {60 assertThat(and(True, True).evaluate(Set.of())).isTrue();61 assertThat(and(True, False).evaluate(Set.of())).isFalse();62 assertThat(and(False, onEvaluateThrow()).evaluate(Set.of())).isFalse();63 }64 @Test65 void encloseOrWithParenthesis() {66 assertThat(or(tag("foo"), tag("bar"))).hasToString("(foo | bar)");67 }68 @Test69 void orEvaluation() {70 assertThat(or(False, False).evaluate(Set.of())).isFalse();71 assertThat(or(True, onEvaluateThrow()).evaluate(Set.of())).isTrue();72 assertThat(or(False, True).evaluate(Set.of())).isTrue();73 }74 @Test75 void anyEvaluation() {76 assertThat(any().evaluate(Set.of())).isFalse();77 assertThat(any().evaluate(Set.of(TestTag.create("foo")))).isTrue();78 }79 @Test80 void noneEvaluation() {81 assertThat(none().evaluate(Set.of())).isTrue();82 assertThat(none().evaluate(Set.of(TestTag.create("foo")))).isFalse();83 }84 private TagExpression onEvaluateThrow() {85 return tags -> {86 throw new RuntimeException("should not be evaluated");87 };88 }89}...
Source:AssertTests.java
...4import static org.hamcrest.CoreMatchers.equalTo;5import static org.hamcrest.CoreMatchers.not;6import static org.hamcrest.CoreMatchers.sameInstance;7import static org.hamcrest.CoreMatchers.startsWith;8import static org.junit.Assert.assertThat;9import static org.junit.matchers.JUnitMatchers.*;10import java.util.Arrays;11import org.hamcrest.core.CombinableMatcher;12import org.junit.Test;13/*14 * ç®çï¼Assertions æè¨æ¹æ³ç使ç¨15 * 16 */17public class AssertTests {18 @Test19 public void testAssertArrayEquals() {20 byte[] expected = "trial".getBytes();21 byte[] actual = "trial".getBytes();22 org.junit.Assert.assertArrayEquals("failure - byte arrays not same", expected, actual);23 }24 @Test25 public void testAssertEquals() {26 org.junit.Assert.assertEquals("failure - strings are not equal", "text", "text");27 }28 @Test29 public void testAssertFalse() {30 org.junit.Assert.assertFalse("failure - should be false", false);31 }32 @Test33 public void testAssertNotNull() {34 org.junit.Assert.assertNotNull("should not be null", new Object());35 }36 @Test37 public void testAssertNotSame() {38 //æ¯è¾ä¸¤ä¸ªå¯¹è±¡çå
åå°å39 org.junit.Assert.assertNotSame("should not be same Object", new Object(), new Object());40 }41 @Test42 public void testAssertNull() {43 org.junit.Assert.assertNull("should be null", null);44 }45 @Test46 public void testAssertSame() {47 Integer aNumber = Integer.valueOf(768);48 org.junit.Assert.assertSame("should be same", aNumber, aNumber);49 }50 // JUnit Matchers assertThat51 @Test52 public void testAssertThatBothContainsString() {53 org.junit.Assert.assertThat("albumen", both(containsString("a")).and(containsString("c")));54 }55 56 @Test57 public void testAssertThatEitherConteinString(){58 org.junit.Assert.assertThat("albumen", either(containsString("al")).or(containsString("men")));59 }60 @Test61 public void testAssertThathasItemsContainsString() {62 org.junit.Assert.assertThat(Arrays.asList("one", "two", "three"), hasItems("one", "three"));63 }64 @Test65 public void testAssertThatEveryItemContainsString() {66 org.junit.Assert.assertThat(Arrays.asList(new String[] { "fun", "ban", "net" }), everyItem(containsString("n")));67 }68 // Core Hamcrest Matchers with assertThat69 @Test70 public void testAssertThatHamcrestCoreMatchers() {71 assertThat("good", allOf(equalTo("good"), startsWith("good")));72 assertThat("good", not(allOf(equalTo("bad"), equalTo("good"))));73 assertThat("good", anyOf(equalTo("bad"), equalTo("good")));74 assertThat(7, not(CombinableMatcher.<Integer> either(equalTo(3)).or(equalTo(4))));75 assertThat(new Object(), not(sameInstance(new Object())));76 }77 @Test78 public void testAssertTrue() {79 org.junit.Assert.assertTrue("failure - should be true", true);80 }81}...
assertThat
Using AI Code Generation
1import static org.junit.Assert.assertThat;2import java.util.Arrays;3import java.util.List;4import org.hamcrest.CoreMatchers;5import org.junit.Test;6public class HamcrestTest {7 public void test() {8 List<Integer> numbers = Arrays.asList(12, 15, 45);9 assertThat(numbers, CoreMatchers.hasItems(12, 45));10 assertThat(numbers, CoreMatchers.everyItem(CoreMatchers.greaterThan(10)));11 assertThat(numbers, CoreMatchers.everyItem(CoreMatchers.lessThan(100)));12 }13}
assertThat
Using AI Code Generation
1import static org.hamcrest.MatcherAssert.assertThat;2import static org.hamcrest.Matchers.*;3import org.junit.Test;4public class HamcrestMatchersTest {5 public void testAssertThatBothContainsString() {6 assertThat("albumen", both(containsString("a")).and(containsString("b")));7 }8 public void testAssertThatHasItems() {9 assertThat(Arrays.asList("one", "two", "three"), hasItems("one", "three"));10 }11 public void testAssertThatEveryItemContainsString() {12 assertThat(Arrays.asList(new String[] { "fun", "ban", "net" }), everyItem(containsString("n")));13 }14 public void testAssertThatHamcrestCoreMatchers() {15 assertThat("good", allOf(equalTo("good"), startsWith("good")));16 assertThat("good", not(allOf(equalTo("bad"), equalTo("good"))));17 assertThat("good", anyOf(equalTo("bad"), equalTo("good")));18 assertThat(7, not(CombinableMatcher.<Integer> either(equalTo(3)).or(equalTo(4))));19 assertThat(new Object(), not(sameInstance(new Object())));20 }21}
LambdaTest also has a detailed JUnit tutorial explaining its features, importance, advanced use cases, best practices, and more to help you get started with running your automation testing scripts.
Here are the detailed JUnit testing chapters to help you get started:
You can also check out our JUnit certification if you wish to take your career in Selenium automation testing with JUnit to the next level.
Get 100 minutes of automation test minutes FREE!!