Best junit code snippet using org.junit.runner.JUnitCore.run
Source: OrderableTest.java
...3import junit.framework.JUnit4TestAdapter;4import org.junit.Before;5import org.junit.FixMethodOrder;6import org.junit.Test;7import org.junit.experimental.runners.Enclosed;8import org.junit.runner.Description;9import org.junit.runner.JUnitCore;10import org.junit.runner.Request;11import org.junit.runner.RunWith;12import org.junit.runner.Runner;13import org.junit.runner.manipulation.Orderer;14import org.junit.runner.manipulation.InvalidOrderingException;15import org.junit.runner.manipulation.Orderable;16import org.junit.runner.manipulation.Sorter;17import org.junit.runner.notification.RunNotifier;18import org.junit.runners.BlockJUnit4ClassRunner;19import org.junit.runners.MethodSorters;20@RunWith(Enclosed.class)21public class OrderableTest {22 public static class TestClassRunnerIsOrderable {23 private static String log = "";24 @Before25 public void resetLog() {26 log = "";27 }28 @Test29 public void orderingForwardWorksOnTestClassRunner() {30 Request forward = Request.aClass(OrderMe.class).orderWith(31 AlphanumericOrdering.INSTANCE);32 new JUnitCore().run(forward);33 assertEquals("abc", log);34 }35 @Test36 public void orderingBackwardWorksOnTestClassRunner() {37 Request backward = Request.aClass(OrderMe.class).orderWith(38 new ReverseAlphanumericOrdering());39 new JUnitCore().run(backward);40 assertEquals("cba", log);41 }42 @Test43 public void orderingBackwardDoesNothingOnTestClassRunnerWithFixMethodOrder() {44 Request backward = Request.aClass(DoNotOrderMe.class).orderWith(45 new ReverseAlphanumericOrdering());46 new JUnitCore().run(backward);47 assertEquals("abc", log);48 }49 @Test50 public void orderingForwardWorksOnSuite() {51 Request forward = Request.aClass(Enclosing.class).orderWith(52 AlphanumericOrdering.INSTANCE);53 new JUnitCore().run(forward);54 assertEquals("AaAbAcBaBbBc", log);55 }56 @Test57 public void orderingBackwardWorksOnSuite() {58 Request backward = Request.aClass(Enclosing.class).orderWith(59 new ReverseAlphanumericOrdering());60 new JUnitCore().run(backward);61 assertEquals("BcBbBaAcAbAa", log);62 }63 public static class OrderMe {64 @Test65 public void a() {66 log += "a";67 }68 @Test69 public void b() {70 log += "b";71 }72 @Test73 public void c() {74 log += "c";75 }76 }77 @FixMethodOrder(MethodSorters.NAME_ASCENDING)78 public static class DoNotOrderMe {79 @Test80 public void a() {81 log += "a";82 }83 @Test84 public void b() {85 log += "b";86 }87 @Test88 public void c() {89 log += "c";90 }91 }92 @RunWith(Enclosed.class)93 public static class Enclosing {94 public static class A {95 @Test96 public void a() {97 log += "Aa";98 }99 @Test100 public void b() {101 log += "Ab";102 }103 @Test104 public void c() {105 log += "Ac";106 }107 }108 public static class B {109 @Test110 public void a() {111 log += "Ba";112 }113 @Test114 public void b() {115 log += "Bb";116 }117 @Test118 public void c() {119 log += "Bc";120 }121 }122 }123 }124 public static class TestOrderableClassRunnerIsSortable {125 private static String log = "";126 @Before127 public void resetLog() {128 log = "";129 }130 @Test131 public void orderingorwardWorksOnTestClassRunner() {132 Request forward = Request.aClass(OrderMe.class).orderWith(133 AlphanumericOrdering.INSTANCE);134 new JUnitCore().run(forward);135 assertEquals("abc", log);136 }137 @Test138 public void orderedBackwardWorksOnTestClassRunner() {139 Request backward = Request.aClass(OrderMe.class).orderWith(140 new ReverseAlphanumericOrdering());141 new JUnitCore().run(backward);142 assertEquals("cba", log);143 }144 /**145 * A Runner that implements {@link Orderable}.146 */147 public static class OrderableRunner extends Runner implements Orderable {148 private final BlockJUnit4ClassRunner delegate;149 public OrderableRunner(Class<?> klass) throws Throwable {150 delegate = new BlockJUnit4ClassRunner(klass);151 }152 @Override153 public void run(RunNotifier notifier) {154 delegate.run(notifier);155 }156 @Override157 public Description getDescription() {158 return delegate.getDescription();159 }160 public void order(Orderer orderer) throws InvalidOrderingException {161 delegate.order(orderer);162 }163 public void sort(Sorter sorter) {164 delegate.sort(sorter);165 }166 }167 @RunWith(OrderableRunner.class)168 public static class OrderMe {169 @Test170 public void a() {171 log += "a";172 }173 @Test174 public void b() {175 log += "b";176 }177 @Test178 public void c() {179 log += "c";180 }181 }182 }183 public static class TestClassRunnerIsOrderableWithSuiteMethod {184 private static String log = "";185 @Before186 public void resetLog() {187 log = "";188 }189 @Test190 public void orderingForwardWorksOnTestClassRunner() {191 Request forward = Request.aClass(OrderMe.class).orderWith(AlphanumericOrdering.INSTANCE);192 new JUnitCore().run(forward);193 assertEquals("abc", log);194 }195 @Test196 public void orderingBackwardWorksOnTestClassRunner() {197 Request backward = Request.aClass(OrderMe.class).orderWith(198 new ReverseAlphanumericOrdering());199 new JUnitCore().run(backward);200 assertEquals("cba", log);201 }202 public static class OrderMe {203 public static junit.framework.Test suite() {204 return new JUnit4TestAdapter(OrderMe.class);205 }206 @Test207 public void a() {208 log += "a";209 }210 @Test211 public void b() {212 log += "b";213 }214 @Test215 public void c() {216 log += "c";217 }218 }219 }220 public static class UnOrderableRunnersAreHandledWithoutCrashing {221 @Test222 public void unOrderablesAreHandledWithoutCrashing() {223 Request unordered = Request.aClass(UnOrderable.class).orderWith(224 AlphanumericOrdering.INSTANCE);225 new JUnitCore().run(unordered);226 }227 public static class UnOrderableRunner extends Runner {228 public UnOrderableRunner(Class<?> klass) {229 }230 @Override231 public Description getDescription() {232 return Description.EMPTY;233 }234 @Override235 public void run(RunNotifier notifier) {236 }237 }238 @RunWith(UnOrderableRunner.class)239 public static class UnOrderable {240 @Test241 public void a() {242 }243 }244 }245}...
Source: ParentRunnerFilteringTest.java
1package org.junit.tests.running.classes;2import static org.junit.Assert.assertEquals;3import static org.junit.Assert.assertThat;4import static org.junit.Assert.fail;5import static org.junit.experimental.results.PrintableResult.testResult;6import static org.junit.experimental.results.ResultMatchers.hasSingleFailureContaining;7import static org.junit.runner.Description.createSuiteDescription;8import static org.junit.runner.Description.createTestDescription;9import java.util.Collections;10import java.util.HashMap;11import java.util.List;12import java.util.Map;13import org.junit.Test;14import org.junit.runner.Description;15import org.junit.runner.JUnitCore;16import org.junit.runner.Request;17import org.junit.runner.Result;18import org.junit.runner.RunWith;19import org.junit.runner.Runner;20import org.junit.runner.manipulation.Filter;21import org.junit.runner.manipulation.NoTestsRemainException;22import org.junit.runners.Suite;23import org.junit.runners.Suite.SuiteClasses;24import org.junit.runners.model.InitializationError;25import org.junit.runners.model.RunnerBuilder;26public class ParentRunnerFilteringTest {27 private static Filter notThisMethodName(final String methodName) {28 return new Filter() {29 @Override30 public boolean shouldRun(Description description) {31 return description.getMethodName() == null32 || !description.getMethodName().equals(methodName);33 }34 @Override35 public String describe() {36 return "don't run method name: " + methodName;37 }38 };39 }40 private static class CountingFilter extends Filter {41 private final Map<Description, Integer> countMap = new HashMap<Description, Integer>();42 @Override43 public boolean shouldRun(Description description) {44 Integer count = countMap.get(description);45 if (count == null) {46 countMap.put(description, 1);47 } else {48 countMap.put(description, count + 1);49 }50 return true;51 }52 @Override53 public String describe() {54 return "filter counter";55 }56 public int getCount(final Description desc) {57 if (!countMap.containsKey(desc)) {58 throw new IllegalArgumentException("Looking for " + desc59 + ", but only contains: " + countMap.keySet());60 }61 return countMap.get(desc);62 }63 }64 public static class ExampleTest {65 @Test66 public void test1() throws Exception {67 // passes68 }69 }70 @RunWith(Suite.class)71 @SuiteClasses({ExampleTest.class})72 public static class ExampleSuite {73 }74 @Test75 public void testSuiteFiltering() throws Exception {76 Runner runner = Request.aClass(ExampleSuite.class).getRunner();77 Filter filter = notThisMethodName("test1");78 try {79 filter.apply(runner);80 } catch (NoTestsRemainException e) {81 return;82 }83 fail("Expected 'NoTestsRemainException' due to complete filtering");84 }85 public static class SuiteWithUnmodifyableChildList extends Suite {86 public SuiteWithUnmodifyableChildList(87 Class<?> klass, RunnerBuilder builder)88 throws InitializationError {89 super(klass, builder);90 }91 @Override92 protected List<Runner> getChildren() {93 return Collections.unmodifiableList(super.getChildren());94 }95 }96 @RunWith(SuiteWithUnmodifyableChildList.class)97 @SuiteClasses({ExampleTest.class})98 public static class ExampleSuiteWithUnmodifyableChildList {99 }100 @Test101 public void testSuiteFilteringWithUnmodifyableChildList() throws Exception {102 Runner runner = Request.aClass(ExampleSuiteWithUnmodifyableChildList.class)103 .getRunner();104 Filter filter = notThisMethodName("test1");105 try {106 filter.apply(runner);107 } catch (NoTestsRemainException e) {108 return;109 }110 fail("Expected 'NoTestsRemainException' due to complete filtering");111 }112 @Test113 public void testRunSuiteFiltering() throws Exception {114 Request request = Request.aClass(ExampleSuite.class);115 Request requestFiltered = request.filterWith(notThisMethodName("test1"));116 assertThat(testResult(requestFiltered),117 hasSingleFailureContaining("don't run method name: test1"));118 }119 @Test120 public void testCountClassFiltering() throws Exception {121 JUnitCore junitCore = new JUnitCore();122 Request request = Request.aClass(ExampleTest.class);123 CountingFilter countingFilter = new CountingFilter();124 Request requestFiltered = request.filterWith(countingFilter);125 Result result = junitCore.run(requestFiltered);126 assertEquals(1, result.getRunCount());127 assertEquals(0, result.getFailureCount());128 Description desc = createTestDescription(ExampleTest.class, "test1");129 assertEquals(1, countingFilter.getCount(desc));130 }131 @Test132 public void testCountSuiteFiltering() throws Exception {133 Class<ExampleSuite> suiteClazz = ExampleSuite.class;134 Class<ExampleTest> clazz = ExampleTest.class;135 JUnitCore junitCore = new JUnitCore();136 Request request = Request.aClass(suiteClazz);137 CountingFilter countingFilter = new CountingFilter();138 Request requestFiltered = request.filterWith(countingFilter);139 Result result = junitCore.run(requestFiltered);140 assertEquals(1, result.getRunCount());141 assertEquals(0, result.getFailureCount());142 Description suiteDesc = createSuiteDescription(clazz);143 assertEquals(1, countingFilter.getCount(suiteDesc));144 Description desc = createTestDescription(ExampleTest.class, "test1");145 assertEquals(1, countingFilter.getCount(desc));146 }147}...
Source: JUnitCore.java
1package org.junit.runner;23import java.util.ArrayList;4import java.util.List;56import junit.runner.Version;7import org.junit.internal.runners.OldTestClassRunner;8import org.junit.internal.runners.TextListener;9import org.junit.runner.notification.Failure;10import org.junit.runner.notification.RunListener;11import org.junit.runner.notification.RunNotifier;1213/**14 * <code>JUnitCore</code> is a facade for running tests. It supports running JUnit 4 tests, 15 * JUnit 3.8.x tests, and mixtures. To run tests from the command line, run 16 * <code>java org.junit.runner.JUnitCore TestClass1 TestClass2 ...</code>.17 * For one-shot test runs, use the static method {@link #runClasses(Class[])}. 18 * If you want to add special listeners,19 * create an instance of {@link org.junit.runner.JUnitCore} first and use it to run the tests.20 * 21 * @see org.junit.runner.Result22 * @see org.junit.runner.notification.RunListener23 * @see org.junit.runner.Request24 */25public class JUnitCore {26 27 private RunNotifier fNotifier;2829 /**30 * Create a new <code>JUnitCore</code> to run tests.31 */32 public JUnitCore() {33 fNotifier= new RunNotifier();34 }3536 /**37 * Run the tests contained in the classes named in the <code>args</code>.38 * If all tests run successfully, exit with a status of 0. Otherwise exit with a status of 1.39 * Write feedback while tests are running and write40 * stack traces for all failed tests after the tests all complete.41 * @param args names of classes in which to find tests to run42 */43 public static void main(String... args) {44 Result result= new JUnitCore().runMain(args);45 killAllThreads(result);46 }4748 private static void killAllThreads(Result result) {49 System.exit(result.wasSuccessful() ? 0 : 1);50 }51 52 /**53 * Run the tests contained in <code>classes</code>. Write feedback while the tests54 * are running and write stack traces for all failed tests after all tests complete. This is55 * similar to {@link #main(String[])}, but intended to be used programmatically.56 * @param classes Classes in which to find tests57 * @return a {@link Result} describing the details of the test run and the failed tests.58 */59 public static Result runClasses(Class<?>... classes) {60 return new JUnitCore().run(classes);61 }62 63 /**64 * Do not use. Testing purposes only.65 */66 public Result runMain(String... args) {67 System.out.println("JUnit version " + Version.id());68 List<Class<?>> classes= new ArrayList<Class<?>>();69 List<Failure> missingClasses= new ArrayList<Failure>();70 for (String each : args)71 try {72 classes.add(Class.forName(each));73 } catch (ClassNotFoundException e) {74 System.out.println("Could not find class: " + each);75 Description description= Description.createSuiteDescription(each);76 Failure failure= new Failure(description, e);77 missingClasses.add(failure);78 }79 RunListener listener= new TextListener();80 addListener(listener);81 Result result= run(classes.toArray(new Class[0]));82 for (Failure each : missingClasses)83 result.getFailures().add(each);84 return result;85 }8687 /**88 * @return the version number of this release89 */90 public String getVersion() {91 return Version.id();92 }93 94 /**95 * Run all the tests in <code>classes</code>.96 * @param classes the classes containing tests97 * @return a {@link Result} describing the details of the test run and the failed tests.98 */99 public Result run(Class<?>... classes) {100 return run(Request.classes("All", classes));101 }102103 /**104 * Run all the tests contained in <code>request</code>.105 * @param request the request describing tests106 * @return a {@link Result} describing the details of the test run and the failed tests.107 */108 public Result run(Request request) {109 return run(request.getRunner());110 }111112 /**113 * Run all the tests contained in JUnit 3.8.x <code>test</code>. Here for backward compatibility.114 * @param test the old-style test115 * @return a {@link Result} describing the details of the test run and the failed tests.116 */117 public Result run(junit.framework.Test test) { 118 return run(new OldTestClassRunner(test));119 }120 121 /**122 * Do not use. Testing purposes only.123 */124 public Result run(Runner runner) {125 Result result= new Result();126 RunListener listener= result.createListener();127 addFirstListener(listener);128 try {129 fNotifier.fireTestRunStarted(runner.getDescription());130 runner.run(fNotifier);131 fNotifier.fireTestRunFinished(result);132 } finally {133 removeListener(listener);134 }135 return result;136 }137 138 private void addFirstListener(RunListener listener) {139 fNotifier.addFirstListener(listener);140 }141 142143 /**144 * Add a listener to be notified as the tests run.145 * @param listener the listener to add146 * @see org.junit.runner.notification.RunListener147 */148 public void addListener(RunListener listener) {149 fNotifier.addListener(listener);150 }151152 /**153 * Remove a listener.154 * @param listener the listener to remove155 */156 public void removeListener(RunListener listener) {157 fNotifier.removeListener(listener);158 }159}
Source: AllTests.java
1package sketch.compiler.smt.cvc3;2import static org.junit.Assert.*;3import org.junit.Test;4import org.junit.runner.Result;5public class AllTests {6 7 public static void main(String[] args) {8 Result runClasses = org.junit.runner.JUnitCore.runClasses(LanguageBasicTOAInt.class);9 assertTrue("Failed count is " + runClasses.getFailureCount(),10 runClasses.getFailureCount() == 0);11 }12 13 @Test14 public void languageBasicTOAIntTests() {15 Result runClasses = org.junit.runner.JUnitCore.runClasses(LanguageBasicTOAInt.class);16 assertTrue("Failed count is " + runClasses.getFailureCount(),17 runClasses.getFailureCount() == 0);18 }19 @Test20 public void languageBasicBlastIntTests() {21 Result runClasses = org.junit.runner.JUnitCore.runClasses(LanguageBasicBlastInt.class);22 assertTrue("Failed count is " + runClasses.getFailureCount(),23 runClasses.getFailureCount() == 0);24 }25 26 @Test27 public void languageBasicTOABVTests() {28 Result runClasses = org.junit.runner.JUnitCore.runClasses(LanguageBasicTOABV.class);29 assertTrue("Failed count is " + runClasses.getFailureCount(),30 runClasses.getFailureCount() == 0);31 }32 @Test33 public void languageBasicBlastBVTests() {34 Result runClasses = org.junit.runner.JUnitCore.runClasses(LanguageBasicBlastBV.class);35 assertTrue("Failed count is " + runClasses.getFailureCount(),36 runClasses.getFailureCount() == 0);37 }38 39 @Test40 public void loopTOAIntTests() {41 Result runClasses = org.junit.runner.JUnitCore.runClasses(LoopTOAInt.class);42 assertTrue("Failed count is " + runClasses.getFailureCount(),43 runClasses.getFailureCount() == 0);44 }45 46 @Test47 public void loopTOABVTests() {48 Result runClasses = org.junit.runner.JUnitCore.runClasses(LoopTOABV.class);49 assertTrue("Failed count is " + runClasses.getFailureCount(),50 runClasses.getFailureCount() == 0);51 }52 53 @Test54 public void loopBlastIntTests() {55 Result runClasses = org.junit.runner.JUnitCore.runClasses(LoopBlastInt.class);56 assertTrue("Failed count is " + runClasses.getFailureCount(),57 runClasses.getFailureCount() == 0);58 }59 60 @Test61 public void loopBlastBVTests() {62 Result runClasses = org.junit.runner.JUnitCore.runClasses(LoopBlastBV.class);63 assertTrue("Failed count is " + runClasses.getFailureCount(),64 runClasses.getFailureCount() == 0);65 }66 67 @Test68 public void regularExprTOAIntTests() {69 Result runClasses = org.junit.runner.JUnitCore.runClasses(RegularExprTOAInt.class);70 assertTrue("Failed count is " + runClasses.getFailureCount(),71 runClasses.getFailureCount() == 0);72 }73 74 @Test75 public void regularExprTOABVTests() {76 Result runClasses = org.junit.runner.JUnitCore.runClasses(RegularExprTOABV.class);77 assertTrue("Failed count is " + runClasses.getFailureCount(),78 runClasses.getFailureCount() == 0);79 }80 81 @Test82 public void regularExprBlastIntTests() {83 Result runClasses = org.junit.runner.JUnitCore.runClasses(RegularExprBlastInt.class);84 assertTrue("Failed count is " + runClasses.getFailureCount(),85 runClasses.getFailureCount() == 0);86 }87 88 @Test89 public void regularExprBlastBVTests() {90 Result runClasses = org.junit.runner.JUnitCore.runClasses(RegularExprBlastBV.class);91 assertTrue("Failed count is " + runClasses.getFailureCount(),92 runClasses.getFailureCount() == 0);93 }94 95}...
Source: TestRunner.java
...4 * and open the template in the editor.5 */6package org.inventory.db;7import javax.naming.spi.DirStateFactory.Result;8import org.junit.runner.JUnitCore;9import org.junit.runner.notification.Failure;10/**11 *12 * @author sampanit13 */14public class TestRunner {15 public static void main(String[] args) {16 org.junit.runner.Result databaseResult = JUnitCore.runClasses(DatabaseTest.class);17 org.junit.runner.Result productManagerResult = JUnitCore.runClasses(ProductManagerTest.class);18 org.junit.runner.Result supplierManagerResult = JUnitCore.runClasses(SupplierManagerTest.class);19 org.junit.runner.Result customerManagerResult = JUnitCore.runClasses(CustomerManagerTest.class);20 org.junit.runner.Result profileManagerResult = JUnitCore.runClasses(ProfileManagerTest.class);21//before run PurchaseManagerTest.Class you must be set supplier UserId . this is the dependency of PurchaseManagerTest class 22 org.junit.runner.Result purchaseManagerResult = JUnitCore.runClasses(PurchaseManagerTest.class);23//before run SaleManagerTest.class you must be set customer UserId . this is the dependency of PurchaseManagerTest class24 org.junit.runner.Result saleManagerResult = JUnitCore.runClasses(SaleManagerTest.class);25 org.junit.runner.Result stockManagerResult = JUnitCore.runClasses(StockManagerTest.class);26 for (Failure failure : databaseResult.getFailures()) {27 System.out.println(failure.toString());28 }29 System.out.println(databaseResult.wasSuccessful());30 for (Failure failure : productManagerResult.getFailures()) {31 System.out.println(failure.toString());32 }33 System.out.println(productManagerResult.wasSuccessful());34 for (Failure failure : supplierManagerResult.getFailures()) {35 System.out.println(failure.toString());36 }37 System.out.println(supplierManagerResult.wasSuccessful());38 for (Failure failure : customerManagerResult.getFailures()) {39 System.out.println(failure.toString());...
Source: TestExecutor.java
1//package com.alibaba.cola.mock.container;2//3//import java.lang.reflect.Constructor;4//5//import org.junit.runner.Description;6//import org.junit.runner.JUnitCore;7//import org.junit.runner.RunWith;8//import org.junit.runner.Runner;9//import org.junit.runner.manipulation.Filter;10//import org.junit.runner.manipulation.Filterable;11//import org.junit.runner.notification.Failure;12//import org.junit.runner.notification.RunListener;13//import org.slf4j.Logger;14//import org.slf4j.LoggerFactory;15//16///**17// *18// * @author shawnzhan.zxy19// * @date 2018/09/1420// */21//public class TestExecutor {22// private static final Logger logger = LoggerFactory.getLogger(TestExecutor.class);23// private String className;24// private String methodName;25//26// public void testClass() throws Exception {27// Class<?> testClz = Class.forName(className);28// runTest(testClz, null);29// }30//31// public void testMethod() throws Exception {32// Class<?> testClz = Class.forName(className);33// runTest(testClz, new Filter() {34// @Override35// public boolean shouldRun(Description description) {36// if(methodName.equals(description.getMethodName())){37// return true;38// }39// return false;40// }41//42// @Override43// public String describe() {44// return methodName;45// }46// });47// }48//49// private void runTest(Class<?> testClz, Filter filter) throws Exception {50// RunWith runWith = testClz.getAnnotation(RunWith.class);51// Constructor constructor = runWith.value().getConstructor(Class.class);52// Object runner = constructor.newInstance(testClz);53// if(filter != null) {54// ((Filterable)runner).filter(filter);55// }56// JUnitCore jUnitCore = new JUnitCore();57// jUnitCore.addListener(new RunListener(){58// @Override59// public void testFailure(Failure failure) throws Exception {60// logger.error(failure.getDescription().getDisplayName() + " error!", failure.getException());61// }62//63// @Override64// public void testFinished(Description description) throws Exception {65// logger.info(description.getClassName() + " " + description.getDisplayName() + " end.");66// }67//68// @Override69// public void testStarted(Description description) throws Exception {70// logger.info(description.getClassName() + " " + description.getDisplayName() + " start...");71// }72// });73// jUnitCore.run((Runner)runner);74// }75//76// /**77// * @param className the className to set78// */79// public void setClassName(String className) {80// this.className = className;81// }82//83// /**84// * @param methodName the methodName to set85// */86// public void setMethodName(String methodName) {87// this.methodName = methodName;...
Source: JunitRunnerHelper.java
...16package org.drools.workbench.screens.scenariosimulation.backend.server.util;17import java.util.ArrayList;18import java.util.List;19import org.guvnor.common.services.shared.test.Failure;20import org.junit.runner.JUnitCore;21import org.junit.runner.Result;22import org.junit.runner.Runner;23import org.junit.runner.notification.RunListener;24import org.uberfire.backend.vfs.Path;25public class JunitRunnerHelper {26 public static Result runWithJunit(Path path,27 Runner runner,28 List<Failure> failures,29 List<Failure> failureDetails) {30 JUnitCore jUnitCore = new JUnitCore();31 jUnitCore.addListener(new RunListener() {32 @Override33 public void testAssumptionFailure(org.junit.runner.notification.Failure failure) {34 failureDetails.add(failureToFailure(path, failure));35 }36 });37 Result result = jUnitCore.run(runner);38 failures.addAll(failuresToFailures(path, result.getFailures()));39 return result;40 }41 static List<org.guvnor.common.services.shared.test.Failure> failuresToFailures(final Path path,42 final List<org.junit.runner.notification.Failure> failures) {43 List<org.guvnor.common.services.shared.test.Failure> result = new ArrayList<>();44 for (org.junit.runner.notification.Failure failure : failures) {45 result.add(failureToFailure(path, failure));46 }47 return result;48 }49 static org.guvnor.common.services.shared.test.Failure failureToFailure(final Path path,50 final org.junit.runner.notification.Failure failure) {51 return new org.guvnor.common.services.shared.test.Failure(52 getScenarioName(failure),53 failure.getMessage(),54 path);55 }56 static String getScenarioName(final org.junit.runner.notification.Failure failure) {57 return failure.getDescription().getDisplayName();58 }59}...
Source: TestListenerTest.java
1package org.junit.tests.listening;2import static org.junit.Assert.assertEquals;3import static org.junit.Assert.assertNotSame;4import org.junit.Test;5import org.junit.runner.Description;6import org.junit.runner.JUnitCore;7import org.junit.runner.Result;8import org.junit.runner.notification.Failure;9import org.junit.runner.notification.RunListener;10public class TestListenerTest {11 int count;12 class ErrorListener extends RunListener {13 @Override14 public void testRunStarted(Description description) throws Exception {15 throw new Error();16 }17 }18 public static class OneTest {19 @Test20 public void nothing() {21 }22 }23 @Test(expected = Error.class)24 public void failingListener() {25 JUnitCore runner = new JUnitCore();26 runner.addListener(new ErrorListener());27 runner.run(OneTest.class);28 }29 class ExceptionListener extends ErrorListener {30 @Override31 public void testRunStarted(Description description) throws Exception {32 count++;33 throw new Exception();34 }35 }36 @Test37 public void reportsFailureOfListener() {38 JUnitCore core = new JUnitCore();39 core.addListener(new ExceptionListener());40 count = 0;41 Result result = core.run(OneTest.class);42 assertEquals(1, count);43 assertEquals(1, result.getFailureCount());44 Failure testFailure = result.getFailures().get(0);45 assertEquals(Description.TEST_MECHANISM, testFailure.getDescription());46 }47 @Test48 public void freshResultEachTime() {49 JUnitCore core = new JUnitCore();50 Result first = core.run(OneTest.class);51 Result second = core.run(OneTest.class);52 assertNotSame(first, second);53 }54}...
run
Using AI Code Generation
1import org.junit.runner.JUnitCore;2import org.junit.runner.Result;3import org.junit.runner.notification.Failure;4public class TestRunner {5 public static void main(String[] args) {6 Result result = JUnitCore.runClasses(TestJunit.class);7 for (Failure failure : result.getFailures()) {8 System.out.println(failure.toString());9 }10 System.out.println(result.wasSuccessful());11 }12}13 at org.junit.Assert.assertEquals(Assert.java:115)14 at org.junit.Assert.assertEquals(Assert.java:144)15 at TestJunit.testAdd(TestJunit.java:12)16 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)17 at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)18 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)19 at java.lang.reflect.Method.invoke(Method.java:498)20 at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)21 at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)22 at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)23 at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)24 at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)25 at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)26 at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)27 at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)28 at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)29 at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)30 at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)31 at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)32 at org.junit.runners.ParentRunner.run(ParentRunner.java:363)33 at org.junit.runner.JUnitCore.run(JUnitCore.java:137)34 at org.junit.runner.JUnitCore.run(JUnitCore.java:115)35 at TestRunner.main(TestRunner.java:10)
run
Using AI Code Generation
1import org.junit.runner.JUnitCore;2import org.junit.runner.Result;3import org.junit.runner.notification.Failure;4import org.junit.runner.RunWith;5import org.junit.runners.Suite;6import org.junit.runners.Suite.SuiteClasses;7@RunWith(Suite.class)8@SuiteClasses({ TestJunit1.class, TestJunit2.class })9public class TestSuite {10 public static void main(String[] args) {11 Result result = JUnitCore.runClasses(TestSuite.class);12 for (Failure failure : result.getFailures()) {13 System.out.println(failure.toString());14 }15 System.out.println(result.wasSuccessful());16 }17}
Easier DynamoDB local testing
Is there a way to run MySQL in-memory for JUnit test cases?
Tests not running through Maven?
maven error: package org.junit does not exist
ant junit task does not report detail
IntelliJ IDEA with Junit 4.7 "!!! JUnit version 3.8 or later expected:"
passing Parameterized input using Mockitos
JUnit assertEquals(double expected, double actual, double epsilon)
How to deal with relative path in Junits between Maven and Intellij
Executing JUnit 4 and JUnit 5 tests in a same build
In order to use DynamoDBLocal you need to follow these steps.
sqlite4java.library.path
to show native libraries1. Get Direct DynamoDBLocal Dependency
This one is the easy one. You need this repository as explained here.
<!--Dependency:-->
<dependencies>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>DynamoDBLocal</artifactId>
<version>1.11.0.1</version>
<scope></scope>
</dependency>
</dependencies>
<!--Custom repository:-->
<repositories>
<repository>
<id>dynamodb-local</id>
<name>DynamoDB Local Release Repository</name>
<url>https://s3-us-west-2.amazonaws.com/dynamodb-local/release</url>
</repository>
</repositories>
2. Get Native SQLite4Java dependencies
If you do not add these dependencies, your tests will fail with 500 internal error.
First, add these dependencies:
<dependency>
<groupId>com.almworks.sqlite4java</groupId>
<artifactId>sqlite4java</artifactId>
<version>1.0.392</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.almworks.sqlite4java</groupId>
<artifactId>sqlite4java-win32-x86</artifactId>
<version>1.0.392</version>
<type>dll</type>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.almworks.sqlite4java</groupId>
<artifactId>sqlite4java-win32-x64</artifactId>
<version>1.0.392</version>
<type>dll</type>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.almworks.sqlite4java</groupId>
<artifactId>libsqlite4java-osx</artifactId>
<version>1.0.392</version>
<type>dylib</type>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.almworks.sqlite4java</groupId>
<artifactId>libsqlite4java-linux-i386</artifactId>
<version>1.0.392</version>
<type>so</type>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.almworks.sqlite4java</groupId>
<artifactId>libsqlite4java-linux-amd64</artifactId>
<version>1.0.392</version>
<type>so</type>
<scope>test</scope>
</dependency>
Then, add this plugin to get native dependencies to specific folder:
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.10</version>
<executions>
<execution>
<id>copy</id>
<phase>test-compile</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<includeScope>test</includeScope>
<includeTypes>so,dll,dylib</includeTypes>
<outputDirectory>${project.basedir}/native-libs</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
3. Set sqlite4java.library.path
to show native libraries
As last step, you need to set sqlite4java.library.path
system property to native-libs directory. It is OK to do that just before creating your local server.
System.setProperty("sqlite4java.library.path", "native-libs");
After these steps you can use DynamoDBLocal as you want. Here is a Junit rule that creates local server for that.
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient;
import com.amazonaws.services.dynamodbv2.local.main.ServerRunner;
import com.amazonaws.services.dynamodbv2.local.server.DynamoDBProxyServer;
import org.junit.rules.ExternalResource;
import java.io.IOException;
import java.net.ServerSocket;
/**
* Creates a local DynamoDB instance for testing.
*/
public class LocalDynamoDBCreationRule extends ExternalResource {
private DynamoDBProxyServer server;
private AmazonDynamoDB amazonDynamoDB;
public LocalDynamoDBCreationRule() {
// This one should be copied during test-compile time. If project's basedir does not contains a folder
// named 'native-libs' please try '$ mvn clean install' from command line first
System.setProperty("sqlite4java.library.path", "native-libs");
}
@Override
protected void before() throws Throwable {
try {
final String port = getAvailablePort();
this.server = ServerRunner.createServerFromCommandLineArgs(new String[]{"-inMemory", "-port", port});
server.start();
amazonDynamoDB = new AmazonDynamoDBClient(new BasicAWSCredentials("access", "secret"));
amazonDynamoDB.setEndpoint("http://localhost:" + port);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
protected void after() {
if (server == null) {
return;
}
try {
server.stop();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public AmazonDynamoDB getAmazonDynamoDB() {
return amazonDynamoDB;
}
private String getAvailablePort() {
try (final ServerSocket serverSocket = new ServerSocket(0)) {
return String.valueOf(serverSocket.getLocalPort());
} catch (IOException e) {
throw new RuntimeException("Available port was not found", e);
}
}
}
You can use this rule like this
@RunWith(JUnit4.class)
public class UserDAOImplTest {
@ClassRule
public static final LocalDynamoDBCreationRule dynamoDB = new LocalDynamoDBCreationRule();
}
Check out the latest blogs from LambdaTest on this topic:
One of the most common test automation challenges is how do we modify the request headers in Selenium WebDriver. As an automation tester, you would come across this challenge for any programming language, including Java. Before coming to the solution, we need to understand the problem statement better and arrive at different possibilities to modify the header request in Java while working with Selenium WebDriver Tutorial.
2020 is finally winding down—and it’s been a challenging year for a lot of us. But we’re pretty sure at this point that when the new year begins, this year will just – vaporize.
There are few javascript testing frameworks makes test automation as easy as running Nightwatch JS testing.
Have you ever been asked for credentials while accessing a website on a browser? Let us understand why we are asked to fill up the credentials while accessing a few websites. This article mainly focuses on the introduction to authentication pop-ups on the website and the different ways to handle them using Selenium. Before we dive in deep and see how to handle login pop-up in Selenium WebDriver, let us first take a look at how the authentication pop-up looks on a website.
While there is a huge demand and need to run Selenium Test Automation, the experts always suggest not to automate every possible test. Exhaustive Testing is not possible, and Automating everything is not sustainable.
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!!