private static void executeTestClass(Class<?> testClass) throws Throwable { Throwable[] throwables = new Throwable[1]; WebTesterJUnitRunner runner = new WebTesterJUnitRunner(testClass); RunNotifier notifier = new RunNotifier(); notifier.addListener(new RunListener() { public void testFailure(Failure failure) throws Exception { System.out.println("testFailure"); throwables[0] = failure.getException(); } }); runner.run(notifier); if (throwables[0] != null) { throw throwables[0]; } }
@Test public void testClassWithPersistenceContextWithKonfiguredUnitNameSpecified() throws Exception { // GIVEN final JCodeModel jCodeModel = new JCodeModel(); final JPackage jp = jCodeModel.rootPackage(); final JDefinedClass jClass = jp._class(JMod.PUBLIC, "ClassUnderTest"); final JFieldVar ruleField = jClass.field(JMod.PUBLIC, JpaUnitRule.class, "rule"); ruleField.annotate(Rule.class); final JInvocation instance = JExpr._new(jCodeModel.ref(JpaUnitRule.class)).arg(JExpr.direct("getClass()")); ruleField.init(instance); final JFieldVar emField = jClass.field(JMod.PRIVATE, EntityManager.class, "em"); final JAnnotationUse jAnnotation = emField.annotate(PersistenceContext.class); jAnnotation.param("unitName", "test-unit-1"); final JMethod jMethod = jClass.method(JMod.PUBLIC, jCodeModel.VOID, "testMethod"); jMethod.annotate(Test.class); buildModel(testFolder.getRoot(), jCodeModel); compileModel(testFolder.getRoot()); final Class<?> cut = loadClass(testFolder.getRoot(), jClass.name()); final BlockJUnit4ClassRunner runner = new BlockJUnit4ClassRunner(cut); final RunListener listener = mock(RunListener.class); final RunNotifier notifier = new RunNotifier(); notifier.addListener(listener); // WHEN runner.run(notifier); // THEN final ArgumentCaptor<Description> descriptionCaptor = ArgumentCaptor.forClass(Description.class); verify(listener).testStarted(descriptionCaptor.capture()); assertThat(descriptionCaptor.getValue().getClassName(), equalTo("ClassUnderTest")); assertThat(descriptionCaptor.getValue().getMethodName(), equalTo("testMethod")); verify(listener).testFinished(descriptionCaptor.capture()); assertThat(descriptionCaptor.getValue().getClassName(), equalTo("ClassUnderTest")); assertThat(descriptionCaptor.getValue().getMethodName(), equalTo("testMethod")); }
public static TestListener run(InputConfiguration configuration, URLClassLoader classLoader, CtType<?> testClass, Collection<String> testMethodNames, RunListener... listeners) { Logger.reset(); Logger.setLogDir(new File(configuration.getInputProgram().getProgramDir() + "/log")); if (testClass.getModifiers().contains(ModifierKind.ABSTRACT)) { final CtTypeReference<?> referenceToAbstractClass = testClass.getReference(); return testClass.getFactory().Class().getAll().stream() .filter(ctType -> ctType.getSuperclass() != null) .filter(ctType -> ctType.getSuperclass().equals(referenceToAbstractClass) ) .map(ctType -> run(configuration, classLoader, ctType, testMethodNames, listeners)) .reduce(new TestListener(), TestListener::aggregate); } return TestRunnerFactory.createRunner(testClass, classLoader).run(testClass.getQualifiedName(), testMethodNames, listeners); }
public static TestListener run(InputConfiguration configuration, String classpath, CtType<?> testClass, Collection<String> testMethodNames, RunListener... listeners) { Logger.reset(); Logger.setLogDir(new File(configuration.getInputProgram().getProgramDir() + "/log")); if (testClass.getModifiers().contains(ModifierKind.ABSTRACT)) { final CtTypeReference<?> referenceToAbstractClass = testClass.getReference(); return testClass.getFactory().Class().getAll().stream() .filter(ctType -> ctType.getSuperclass() != null) .filter(ctType -> ctType.getSuperclass().equals(referenceToAbstractClass) ) .map(subType -> run(configuration, classpath, subType, testMethodNames, listeners)) .reduce(new TestListener(), TestListener::aggregate); } return TestRunnerFactory.createRunner(testClass, classpath).run(testClass.getQualifiedName(), testMethodNames, listeners); }
@Override public TestListener run(Class<?> testClass, Collection<String> testMethodNames, RunListener... additionalListeners) { if (additionalListeners.length != 0) { LOGGER.warn("Additional listeners is not supported for ReflectiveTestRunner"); } ExecutorService executor = Executors.newSingleThreadExecutor(); final Future<?> submit = executor.submit(() -> { Thread.currentThread().setContextClassLoader(classLoader); return runUsingReflection(testClass); }); try { Object listener = submit.get(10000000 * (testMethodNames.size() + 1), TimeUnit.MILLISECONDS); return TestListener.copyFromObject(listener, testMethodNames); } catch (Exception e) { throw new RuntimeException(e); } finally { submit.cancel(true); executor.shutdownNow(); Logger.stopLogging(); Logger.close(); } }
@Test public void simpleValidTestMocked() throws Exception { RunListener listener = runTestWithMockListener(ValidTest.class); ArgumentCaptor<Description> argument = ArgumentCaptor.forClass(Description.class); verify(listener, times(1)).testRunStarted(Mockito.any()); verify(listener, times(3)).testStarted(argument.capture()); verify(listener, times(3)).testFinished(Mockito.any()); verify(listener, times(0)).testAssumptionFailure(Mockito.any()); verify(listener, times(1)).testFailure(Mockito.any()); for (Description d : argument.getAllValues()) { assertTrue(d.getTestClass().equals(ValidTest.class)); assertTrue(d.getChildren().isEmpty()); } }
@Test public void simpleValidTestFilteredTestMethod() throws Exception { RunListener listener = runTestCaseWithMockListener(ValidTest.class, Description.createTestDescription(ValidTest.class, "simplePassingTest")); ArgumentCaptor<Description> argument = ArgumentCaptor.forClass(Description.class); verify(listener, times(1)).testRunStarted(Mockito.any()); verify(listener, times(1)).testStarted(argument.capture()); verify(listener, times(1)).testFinished(Mockito.any()); verify(listener, times(0)).testAssumptionFailure(Mockito.any()); verify(listener, times(0)).testFailure(Mockito.any()); assertEquals("simplePassingTest", argument.getValue().getMethodName()); assertEquals(ValidTest.class, argument.getValue().getTestClass()); assertEquals(0, argument.getValue().getChildren().size()); }
@Test public void simpleValidTestFilteredTheory() throws Exception { RunListener listener = runTestCaseWithMockListener(ValidTest.class, Description.createTestDescription(ValidTest.class, "simpleFailingTheory[true]")); ArgumentCaptor<Description> argument = ArgumentCaptor.forClass(Description.class); verify(listener, times(1)).testRunStarted(Mockito.any()); verify(listener, times(1)).testStarted(argument.capture()); verify(listener, times(1)).testFinished(Mockito.any()); verify(listener, times(0)).testAssumptionFailure(Mockito.any()); verify(listener, times(0)).testFailure(Mockito.any()); assertEquals("simpleFailingTheory[true]", argument.getValue().getMethodName()); assertEquals(ValidTest.class, argument.getValue().getTestClass()); assertEquals(0, argument.getValue().getChildren().size()); }
private void addListeners(List<RunListener> listeners, JUnitCore testRunner, PrintStream writer) { if (getBooleanArgument(ARGUMENT_SUITE_ASSIGNMENT)) { listeners.add(new SuiteAssignmentPrinter()); } else { listeners.add(new TextListener(writer)); listeners.add(new LogRunListener()); mInstrumentationResultPrinter = new InstrumentationResultPrinter(); listeners.add(mInstrumentationResultPrinter); listeners.add(new ActivityFinisherRunListener(this, new ActivityFinisher())); addDelayListener(listeners); addCoverageListener(listeners); } addListenersFromArg(listeners, writer); addListenersFromManifest(listeners, writer); for (RunListener listener : listeners) { testRunner.addListener(listener); if (listener instanceof InstrumentationRunListener) { ((InstrumentationRunListener) listener).setInstrumentation(this); } } }
/** * Sets up listener to inject {@link #ARGUMENT_DELAY_MSEC}, if specified. */ private void addDelayListener(List<RunListener> list) { try { Object delay = getArguments().get(ARGUMENT_DELAY_MSEC); // Accept either string or int if (delay != null) { int delayMsec = Integer.parseInt(delay.toString()); list.add(new DelayInjector(delayMsec)); } else if (getBooleanArgument(ARGUMENT_LOG_ONLY) && Build.VERSION.SDK_INT < 16) { // On older platforms, collecting tests can fail for large volume of tests. // Insert a small delay between each test to prevent this list.add(new DelayInjector(15 /* msec */)); } } catch (NumberFormatException e) { Log.e(LOG_TAG, "Invalid delay_msec parameter", e); } }
/** * Load the listeners specified via meta-data name="listener" in the AndroidManifest. */ private void addListenersFromManifest(List<RunListener> listeners, PrintStream writer) { PackageManager pm = getContext().getPackageManager(); try { InstrumentationInfo instrInfo = pm.getInstrumentationInfo(getComponentName(), PackageManager.GET_META_DATA); Bundle b = instrInfo.metaData; if (b == null) { return; } String extraListenerList = b.getString(ARGUMENT_LISTENER); addListenersFromClassString(extraListenerList, listeners, writer); } catch (NameNotFoundException e) { // should never happen Log.wtf(LOG_TAG, String.format("Could not find component %s", getComponentName())); } }
/** * * @param clazz Set the feature class * @throws InitializationError if there is a problem initializing the test * @throws IOException if there is a problem reading a file */ public ListeningCucumber(final Class clazz) throws InitializationError, IOException { super(clazz); Listener listenerAnnotation = (Listener) clazz .getAnnotation(Listener.class); if (listenerAnnotation != null) { try { listener = (RunListener) listenerAnnotation.value() .newInstance(); } catch (InstantiationException ie) { throw new InitializationError(ie); } catch (IllegalAccessException iae) { throw new InitializationError(iae); } } }
/** * Runs the test classes given in {@param classes}. * * @returns Zero if all tests pass, non-zero otherwise. */ public static int run(Class[] classes, RunListener listener, PrintStream out) { JUnitCore junitCore = new JUnitCore(); junitCore.addListener(listener); boolean hasError = false; int numTests = 0; int numFailures = 0; long start = System.currentTimeMillis(); for (@AutoreleasePool Class c : classes) { out.println("Running " + c.getName()); Result result = junitCore.run(c); numTests += result.getRunCount(); numFailures += result.getFailureCount(); hasError = hasError || !result.wasSuccessful(); } long end = System.currentTimeMillis(); out.println(String.format("Ran %d tests, %d failures. Total time: %s seconds", numTests, numFailures, NumberFormat.getInstance().format((double) (end - start) / 1000))); return hasError ? 1 : 0; }
@Test public void shouldReportDescriptionsinCorrectOrder() { JUnitCore jUnit = new JUnitCore(); jUnit.addListener(new RunListener() { @Override public void testRunStarted(Description description) throws Exception { suiteDescription = description; } }); jUnit.run(CuppaRunnerTest.TestsAndTestBlocks.class); List<Description> rootDescriptionChildren = suiteDescription .getChildren().get(0).getChildren().get(0).getChildren(); assertThat(rootDescriptionChildren).hasSize(3); assertThat(rootDescriptionChildren.get(0).getDisplayName()).startsWith("a"); assertThat(rootDescriptionChildren.get(1).getDisplayName()).startsWith("b"); assertThat(rootDescriptionChildren.get(2).getDisplayName()).startsWith("when c"); assertThat(rootDescriptionChildren.get(2).getChildren().get(0).getDisplayName()).startsWith("d"); }
@Test public void testListener() throws Exception { JUnitCore runner = new JUnitCore(); RunListener listener = new RunListener() { @Override public void testStarted(Description description) { assertEquals(Description.createTestDescription(OneTest.class, "testOne"), description); count++; } }; runner.addListener(listener); count = 0; Result result = runner.run(OneTest.class); assertEquals(1, count); assertEquals(1, result.getRunCount()); }
public AcceptanceTestsRunnerTaskScheduler(final Class[] testClasses, final long initialDelay, final long period, final TimeUnit unit, final List<RunListener> runListeners) { this.testClasses = testClasses; this.initialDelay = initialDelay; this.period = period; this.unit = unit; this.runListeners = runListeners; this.scheduler = Executors.newSingleThreadScheduledExecutor( new ThreadFactoryBuilder() .setNameFormat("acceptance-tests-runner") .setDaemon(false) .build()); }
@Override public void run(RunNotifier notifier) { //a listener that changes the failure's exception in a very hacky way... RunListener listener = new RunListener() { WarningsCollector warningsCollector; @Override public void testStarted(Description description) throws Exception { warningsCollector = new WarningsCollector(); } @Override public void testFailure(final Failure failure) throws Exception { String warnings = warningsCollector.getWarnings(); new JUnitFailureHacker().appendWarnings(failure, warnings); } }; notifier.addFirstListener(listener); runner.run(notifier); }
@Override public void run(RunNotifier notifier) { RunListener listener = new RunListener() { WarningsCollector warningsCollector; @Override public void testStarted(Description description) throws Exception { warningsCollector = new WarningsCollector(); } @Override public void testFailure(Failure failure) throws Exception { logger.log(warningsCollector.getWarnings()); } }; notifier.addListener(listener); runner.run(notifier); }
@Test public void supportsMultipleTestSubjectsPerTraitMethodViaSubjects() throws InitializationError { Traits traits = new Traits(TestSuiteWithOneTraitMethodForMultipleSubjects.class); AtomicInteger testsRun = new AtomicInteger(0); traits.run(new RunNotifier() {{ addListener(new RunListener() { @Override public void testFailure(Failure failure) throws Exception { fail(failure.getMessage()); } @Override public void testFinished(Description description) throws Exception { testsRun.incrementAndGet(); super.testFinished(description); } }); }}); assertEquals(2, testsRun.get()); }
private static void runInternal(final RunNotifier notifier) { try { server = server == null ? new Server() : server; String state = server.getServerState(); serverOptions.setWarFile(new File(SIMPLEWARPATH)).setDebug(true).setBackground(false); if(server.getServerState() == Server.ServerState.STARTED){ server.restartServer(serverOptions); } else { server.startServer(serverOptions); } } catch (Exception e) { throw new RuntimeException(e); } notifier.addListener(new RunListener() { @Override public void testRunFinished(final Result result) throws Exception { server.stopServer(); } }); }
@Override public void run(final RunNotifier notifier){ if (controller.isStarted()) { controller.stop(); } setupServer(); try { controller.start(); } catch (RuntimeException e) { throw new RuntimeException(parameter.getAsVersion() + ": " + e.getMessage(), e); } try { doInject(super.getTestClass().getJavaClass(), null); notifier.addListener(new RunListener() { @Override public void testRunFinished(Result result) throws Exception { super.testRunFinished(result); controller.stop(); largeDeploymentFile.getFile().delete(); } }); super.run(notifier); } finally { controller.stop(); } }
public JUnit4RunnerFactory( Supplier<Request> requestSupplier, Supplier<CancellableRequestFactory> requestFactorySupplier, Supplier<Supplier<TestSuiteModel>> modelSupplierSupplier, Supplier<PrintStream> testRunnerOutSupplier, Supplier<JUnit4Config> configSupplier, Supplier<Set<RunListener>> runListenersSupplier, Supplier<Set<JUnit4Runner.Initializer>> initializersSupplier) { assert requestSupplier != null; this.requestSupplier = requestSupplier; assert requestFactorySupplier != null; this.requestFactorySupplier = requestFactorySupplier; assert modelSupplierSupplier != null; this.modelSupplierSupplier = modelSupplierSupplier; assert testRunnerOutSupplier != null; this.testRunnerOutSupplier = testRunnerOutSupplier; assert configSupplier != null; this.configSupplier = configSupplier; assert runListenersSupplier != null; this.runListenersSupplier = runListenersSupplier; assert initializersSupplier != null; this.initializersSupplier = initializersSupplier; }
public static Factory<JUnit4Runner> create( Supplier<Request> requestSupplier, Supplier<CancellableRequestFactory> requestFactorySupplier, Supplier<Supplier<TestSuiteModel>> modelSupplierSupplier, Supplier<PrintStream> testRunnerOutSupplier, Supplier<JUnit4Config> configSupplier, Supplier<Set<RunListener>> runListenersSupplier, Supplier<Set<JUnit4Runner.Initializer>> initializersSupplier) { return new JUnit4RunnerFactory( requestSupplier, requestFactorySupplier, modelSupplierSupplier, testRunnerOutSupplier, configSupplier, runListenersSupplier, initializersSupplier); }
/** * Creates a runner. */ @Inject JUnit4Runner( Request request, CancellableRequestFactory requestFactory, Supplier<TestSuiteModel> modelSupplier, @Stdout PrintStream testRunnerOut, JUnit4Config config, Set<RunListener> runListeners, Set<Initializer> initializers) { this.request = request; this.requestFactory = requestFactory; this.modelSupplier = modelSupplier; this.config = config; this.testRunnerOut = testRunnerOut; this.runListeners = runListeners; this.initializers = initializers; }
private ByteArrayOutputStream getExpectedOutput(Class<?> testClass) { JUnitCore core = new JUnitCore(); ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); PrintStream printStream = new PrintStream(byteStream); printStream.println("JUnit4 Test Runner"); RunListener listener = new TextListener(printStream); core.addListener(listener); Request request = Request.classWithoutSuiteMethod(testClass); core.run(request); printStream.close(); return byteStream; }
DelegateRunNotifier(Runner runner, RunNotifier delegate, long defaultTestTimeoutMillis) { this.runner = runner; this.delegate = delegate; this.finishedTests = new HashSet<Description>(); this.defaultTestTimeoutMillis = defaultTestTimeoutMillis; this.timer = new Timer(); this.hasTestThatExceededTimeout = new AtomicBoolean(false); // Because our fireTestRunFinished() does not seem to get invoked, we listen for the // delegate to fire a testRunFinished event so we can dispose of the timer. delegate.addListener(new RunListener() { @Override public void testRunFinished(Result result) throws Exception { onTestRunFinished(); } }); }
public JUnitTestClassExecuter(ClassLoader applicationClassLoader, JUnitSpec spec, RunListener listener, TestClassExecutionListener executionListener) { assert executionListener instanceof ThreadSafe; this.applicationClassLoader = applicationClassLoader; this.listener = listener; this.options = spec; this.executionListener = executionListener; }
/** * Do not use. Testing purposes only. */ public Result run(org.junit.runner.Runner runner) { Result result = new Result(); RunListener listener = result.createListener(); notifier.addFirstListener(listener); try { notifier.fireTestRunStarted(runner.getDescription()); runner.run(notifier); notifier.fireTestRunFinished(result); } finally { removeListener(listener); } return result; }
/** * Returns new instance of the JUnit kernel with provided listeners. * * @param listeners an instance (or instances) of JUnit listeners * @return the new instance of the JUnit kernel */ @Override public Junit4Kernel with(RunListener... listeners) { final JUnitCore jUnitCore = new JUnitCore(); Arrays.stream(listeners).forEach(jUnitCore::addListener); return new Junit4Kernel(jUnitCore, this.suiteForRun); }
/** * Méthode takeScreenShot. * @throws SaladiumException */ public String takeScreenShot() { String pathScreenShot = ""; try { String capturePath = AbstractWorker.capturePath; File scrFile = ((TakesScreenshot) this).getScreenshotAs(OutputType.FILE); FileUtil.upload(scrFile.getAbsolutePath(), capturePath + "/" + scrFile.getName()); pathScreenShot = capturePath + "/" + scrFile.getName(); this.logger.info("ScreenShot effectué" + pathScreenShot); } catch (Exception e1) { this.logger.info("takeScreenShot échoué"); e1.printStackTrace(); } // try { // // déconnexion // By decoLocator = By.cssSelector("#logoff > a"); // WebElement webElement = wait.until(ExpectedConditions.elementToBeClickable(decoLocator)); // webElement.click(); // } catch (TimeoutException e) { // Assert.fail("Tentative de forçage de déconnexion après un sreenshot échouée"); // } // A activer si vous souhaitez arrêter les tests dès le premier screenshot effectué (idéal en mode dev ou debug) RunNotifier notifier = new RunNotifier(); Result result = new Result(); RunListener listener = result.createListener(); notifier.addFirstListener(listener); notifier.pleaseStop(); return pathScreenShot; }
/** * Runs the test classes given in {@param classes}. * @returns Zero if all tests pass, non-zero otherwise. */ public static int run(String[] classes, RunListener listener, DopplJunitListener dopplListener) { try { JUnitCore junitCore = new JUnitCore(); if(listener != null) junitCore.addListener(listener); boolean hasError = false; Result result; List<ResultContainer> resultList = new ArrayList<>(classes.length); for (String c : classes) { System.out.println("\n\n********** Running "+ c +" **********"); if(dopplListener != null) dopplListener.startRun(c); result = runSpecificTest(junitCore, c); if(dopplListener != null) dopplListener.endRun(c); resultList.add(new ResultContainer(result, c)); hasError = hasError || !result.wasSuccessful(); } return runInner(resultList, hasError); } catch(ClassNotFoundException e) { throw new RuntimeException(e); } }
/** * Runs the test classes that match settings in {@link #PROPERTIES_FILE_NAME}. * @returns Zero if all tests pass, non-zero otherwise. */ public int run() { Set<Class> classesSet = getTestClasses(); Class[] classes = classesSet.toArray(new Class[classesSet.size()]); sortClasses(classes, sortOrder); RunListener listener = newRunListener(outputFormat); return run(classes, listener, null); }
public static int run(Class[] classes, RunListener listener, DopplJunitListener dopplJunitListener) { List<String> classnameList = new ArrayList<>(); for(Class cl : classes) { classnameList.add(cl.getName()); } return run(classnameList.toArray(new String[classnameList.size()]), listener, dopplJunitListener); }
/** * Returns a new {@link RunListener} instance for the given {@param outputFormat}. */ public RunListener newRunListener(OutputFormat outputFormat) { switch (outputFormat) { case JUNIT: out.println("JUnit version " + Version.id()); return new TextListener(out); case GTM_UNIT_TESTING: return new GtmUnitTestingTextListener(); default: throw new IllegalArgumentException("outputFormat"); } }
@Test public void testClassWithPersistenceUnitWithKonfiguredUnitNameSpecified() throws Exception { // GIVEN final JCodeModel jCodeModel = new JCodeModel(); final JPackage jp = jCodeModel.rootPackage(); final JDefinedClass jClass = jp._class(JMod.PUBLIC, "ClassUnderTest"); final JFieldVar ruleField = jClass.field(JMod.PUBLIC, JpaUnitRule.class, "rule"); ruleField.annotate(Rule.class); final JInvocation instance = JExpr._new(jCodeModel.ref(JpaUnitRule.class)).arg(JExpr.direct("getClass()")); ruleField.init(instance); final JFieldVar emField = jClass.field(JMod.PRIVATE, EntityManagerFactory.class, "emf"); final JAnnotationUse jAnnotation = emField.annotate(PersistenceUnit.class); jAnnotation.param("unitName", "test-unit-1"); final JMethod jMethod = jClass.method(JMod.PUBLIC, jCodeModel.VOID, "testMethod"); jMethod.annotate(Test.class); buildModel(testFolder.getRoot(), jCodeModel); compileModel(testFolder.getRoot()); final Class<?> cut = loadClass(testFolder.getRoot(), jClass.name()); final BlockJUnit4ClassRunner runner = new BlockJUnit4ClassRunner(cut); final RunListener listener = mock(RunListener.class); final RunNotifier notifier = new RunNotifier(); notifier.addListener(listener); // WHEN runner.run(notifier); // THEN final ArgumentCaptor<Description> descriptionCaptor = ArgumentCaptor.forClass(Description.class); verify(listener).testStarted(descriptionCaptor.capture()); assertThat(descriptionCaptor.getValue().getClassName(), equalTo("ClassUnderTest")); assertThat(descriptionCaptor.getValue().getMethodName(), equalTo("testMethod")); verify(listener).testFinished(descriptionCaptor.capture()); assertThat(descriptionCaptor.getValue().getClassName(), equalTo("ClassUnderTest")); assertThat(descriptionCaptor.getValue().getMethodName(), equalTo("testMethod")); }
@Test public void testClassWithoutPersistenceContextField() throws Exception { // GIVEN final JCodeModel jCodeModel = new JCodeModel(); final JPackage jp = jCodeModel.rootPackage(); final JDefinedClass jClass = jp._class(JMod.PUBLIC, "ClassUnderTest"); final JAnnotationUse jAnnotationUse = jClass.annotate(RunWith.class); jAnnotationUse.param("value", JpaUnitRunner.class); final JMethod jMethod = jClass.method(JMod.PUBLIC, jCodeModel.VOID, "testMethod"); jMethod.annotate(Test.class); buildModel(testFolder.getRoot(), jCodeModel); compileModel(testFolder.getRoot()); final Class<?> cut = loadClass(testFolder.getRoot(), jClass.name()); final RunListener listener = mock(RunListener.class); final RunNotifier notifier = new RunNotifier(); notifier.addListener(listener); final JpaUnitRunner runner = new JpaUnitRunner(cut); // WHEN runner.run(notifier); // THEN final ArgumentCaptor<Failure> failureCaptor = ArgumentCaptor.forClass(Failure.class); verify(listener).testFailure(failureCaptor.capture()); final Failure failure = failureCaptor.getValue(); assertThat(failure.getException().getClass(), equalTo(IllegalArgumentException.class)); assertThat(failure.getException().getMessage(), containsString("EntityManagerFactory or EntityManager field annotated")); }
@Test public void testClassWithMultiplePersistenceUnitFields() throws Exception { // GIVEN final JCodeModel jCodeModel = new JCodeModel(); final JPackage jp = jCodeModel.rootPackage(); final JDefinedClass jClass = jp._class(JMod.PUBLIC, "ClassUnderTest"); final JAnnotationUse jAnnotationUse = jClass.annotate(RunWith.class); jAnnotationUse.param("value", JpaUnitRunner.class); final JFieldVar emf1Field = jClass.field(JMod.PRIVATE, EntityManagerFactory.class, "emf1"); emf1Field.annotate(PersistenceUnit.class); final JFieldVar emf2Field = jClass.field(JMod.PRIVATE, EntityManagerFactory.class, "emf2"); emf2Field.annotate(PersistenceUnit.class); final JMethod jMethod = jClass.method(JMod.PUBLIC, jCodeModel.VOID, "testMethod"); jMethod.annotate(Test.class); buildModel(testFolder.getRoot(), jCodeModel); compileModel(testFolder.getRoot()); final Class<?> cut = loadClass(testFolder.getRoot(), jClass.name()); final RunListener listener = mock(RunListener.class); final RunNotifier notifier = new RunNotifier(); notifier.addListener(listener); final JpaUnitRunner runner = new JpaUnitRunner(cut); // WHEN runner.run(notifier); // THEN final ArgumentCaptor<Failure> failureCaptor = ArgumentCaptor.forClass(Failure.class); verify(listener).testFailure(failureCaptor.capture()); final Failure failure = failureCaptor.getValue(); assertThat(failure.getException().getClass(), equalTo(IllegalArgumentException.class)); assertThat(failure.getException().getMessage(), containsString("Only single field is allowed")); }
@Test public void testClassWithPersistenceContextAndPersistenceUnitFields() throws Exception { // GIVEN final JCodeModel jCodeModel = new JCodeModel(); final JPackage jp = jCodeModel.rootPackage(); final JDefinedClass jClass = jp._class(JMod.PUBLIC, "ClassUnderTest"); final JAnnotationUse jAnnotationUse = jClass.annotate(RunWith.class); jAnnotationUse.param("value", JpaUnitRunner.class); final JFieldVar emf1Field = jClass.field(JMod.PRIVATE, EntityManager.class, "em"); emf1Field.annotate(PersistenceContext.class); final JFieldVar emf2Field = jClass.field(JMod.PRIVATE, EntityManagerFactory.class, "emf"); emf2Field.annotate(PersistenceUnit.class); final JMethod jMethod = jClass.method(JMod.PUBLIC, jCodeModel.VOID, "testMethod"); jMethod.annotate(Test.class); buildModel(testFolder.getRoot(), jCodeModel); compileModel(testFolder.getRoot()); final Class<?> cut = loadClass(testFolder.getRoot(), jClass.name()); final RunListener listener = mock(RunListener.class); final RunNotifier notifier = new RunNotifier(); notifier.addListener(listener); final JpaUnitRunner runner = new JpaUnitRunner(cut); // WHEN runner.run(notifier); // THEN final ArgumentCaptor<Failure> failureCaptor = ArgumentCaptor.forClass(Failure.class); verify(listener).testFailure(failureCaptor.capture()); final Failure failure = failureCaptor.getValue(); assertThat(failure.getException().getClass(), equalTo(IllegalArgumentException.class)); assertThat(failure.getException().getMessage(), containsString("either @PersistenceUnit or @PersistenceContext")); }