Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Repo info
Activity
  • Nov 26 14:33
    stale[bot] labeled #2616
  • Nov 26 14:33
    stale[bot] commented #2616
  • Nov 25 17:40
    marcphilipp edited #3083
  • Nov 25 17:39
    marcphilipp labeled #3083
  • Nov 25 17:39
    marcphilipp labeled #3083
  • Nov 25 17:39
    marcphilipp labeled #3083
  • Nov 25 17:39
    marcphilipp unlabeled #3083
  • Nov 25 17:39
    marcphilipp unlabeled #3083
  • Nov 25 17:39
    marcphilipp commented #3083
  • Nov 25 17:38
    marcphilipp closed #3083
  • Nov 25 17:38

    marcphilipp on main

    Upgradle to 7.6 Fix reporting of Enclosed Param… (compare)

  • Nov 25 14:15
    juliette-derancourt assigned #3080
  • Nov 25 11:49
    sbrannen closed #184
  • Nov 25 11:49
    sbrannen commented #184
  • Nov 25 11:29
    marcphilipp commented #3080
  • Nov 25 11:24
    marcphilipp milestoned #3093
  • Nov 25 11:24
    marcphilipp demilestoned #3093
  • Nov 25 00:12
    whiskeysierra commented #871
  • Nov 24 12:16
    ok2c commented #871
  • Nov 24 08:56

    marcphilipp on main

    Upgradle to 7.6-rc-4 (compare)

Francislainy Campos
@francislainy
Hi, I'm trying this for over a year but can't really get it to work and am probably about to give up now. If there's anyone here that may perhaps know what I'm missing, please? https://stackoverflow.com/questions/71848602/how-to-run-junit5-suite-using-the-suite-annotation
19 replies
Thank you very much.
Hi, I'm having this same issue as described on this question posted a few months ago and was wondering if anyone knows a way to bypass this or should it be perhaps reported as a bug on the Github project? It's still related to my question above, as this is what was causing me to attempt using @Suite instead of the RunWith annotation.
Francislainy Campos
@francislainy
image.png
donnd-t
@donnd-t
Is it possible to use ConsoleLauncher with JUnit 5 Extensions? I am trying to run some Spring Boot tests annotated with @SpringBootTest but ConsoleLauncher seems unaware of Spring. The tests run but all my Autowired beans are null. I'm guessing ConsoleLauncher is unaware of SpringExtension?
9 replies
Steve Ebersole
@sebersole
Any word on junit-team/junit5#2393 ?
Been waiting on that for over a year ;)
Joel Moberg
@joelmo
I fail at writing a TestEngine. For some reason the tests I add to root can't be found..
Joel Moberg
@joelmo
I dont understand why. I will just register test dynamically
4 replies
Joel Moberg
@joelmo
How do I register tests in discover()? Adding them to the EngineDescriptor is not enough
mzoffi
@mzoffi
Hi,
I'm having some issue with the LifecycleMethodExecutionExceptionHandler in combination with lifecycle callbacks
in my test i register an extension with an BeforeEachCallback as well as another extension implementing the LifecycleMethodExecutionExceptionHandler
but the LifecycleMethodExecutionExceptionHandler#handleBeforeEachMethodExecutionException is never invokedd from my callback.
has anyone encountered a similar issue?
5 replies
dgoersvocera
@dgoersvocera

Hello, sometimes when I write tests there's a "pre-condition" I want to be evaluated before running the test. However, unlike Assumptions, I don't want to skip the test, I want it to fail or throw an exception.

Is there a helper method for this? I know I can use an assertion, but then it's a little unclear what the test is actually targeting.

Something like this:

        @Test
        @Sql(SQL_SCRIPT)
        void filtersByName() {
            verifyTrue(repository.count() < 2);

            final List<Object> result = repository.findAllByName("helloworld");

            assertEquals(1, result.size());
        }

where verifyTrue fails the test or throws an exception if it's false. Basically I want to make sure no one breaks the seed data file I'm using for this test.

Gilberto J Requena
@gilbertojrequena
Hey guys, I'm giving a look at junit-team/junit5#2087, and I'm wondering if anybody can give me a hint on what should be the behavior of the timeout for each of these modes. I don't want to make any assumptions before starting making the changes.
oscargolding
@oscargolding
Hi, I am running JUnit at a high number of transactions per second using the junit platform launcher (on the same test suite). Despite the test cases passing I keep on running into the following warning emitted from JUnit saying WARNING: Error scanning files for URI jar: ... with the exception java.nio.file.FileSystemAlreadyExistsException due to at jdk.zipfs/jdk.nio.zipfs.ZipFileSystemProvider.newFileSystem(ZipFileSystemProvider.java:102)in org.junit.platform.commons.util.CloseablePath.createForJarFileSystem(CloseablePath.java:57). Ideally I would only like to run test discovery once but the following issue effectively stopped this from happening junit-team/junit5#2379 . I am wondering if there is a way to do test discovery once and reuse an existing TestPlan? Alternatively, is it possible for JUnit to allow concurrent discoveries on the same test suite when the tests are provided to the JVM in .jar format and not unzipped? The warning from JUnit is incredibly noisy when running the launcher frequently across multiple threads on the same test classes. Thanks :)
Vadym
@IakobchukVadym

Hi junit-team ,
I'm trying to implement @AfterAll method which will be executed only once (after all test cases)
I have created Extension:
@Log4j2
public class DataBaseExtension implements BeforeAllCallback, ExtensionContext.Store.CloseableResource {

@Override
public void beforeAll(ExtensionContext extensionContext) {
     log.info("inside beforeAll");
}

@Override
public void close() {
    log.info("DB cleaning started");
    if(!createdUserIds.isEmpty()){
        createdUserIds.forEach(DataBaseExtension::deleteUser);
    }
    clearDBForUser(TESTER_1);
    log.info("DB cleaning started");
}

}
I'm using this extension in my test classes :
@ExtendWith(DataBaseExtension.class)
public class LoginTest {...}

But unfortunately only @beforeAll method is executed
@Override
public void close() {...} is never invoked.
Could you please advise on this?

Vadym
@IakobchukVadym
Already resolved my issue:
    public void beforeAll(ExtensionContext extensionContext) {
        extensionContext.getRoot().getStore(GLOBAL).put("DataBaseExtension", this);
    }
Thomas Hormes
@Tommyten

Hey all,
I'm looking to write tests, which send their results to a backend, which then verifies whether the results are correct.

Obviously the easiest way would be to just have some kind of helper which, after each test as a kind of assertion sends the results to the backend and then lets the test fail/pass.

But I'm thinking that for large Test Suites this could take quite long because of all the Network IO. Because of this I'm looking to write a test engine, which executes all tests, saves the results, sends a big request to the backend (maybe as some kind of map of invocation -> result) and then lets each test either pass/fail depending on what the backend says in its big response, thus reducing the network IO from one call per Test to one call per Testsuite/Testscope.

Has anyone ever done something similar?
Or could somebody point me in the right direction concerning how to get this done?

Sachin Pandey
@sachinp328

Hi all,
i am writing junit test suite using junit 5

package org.apache.commons.csv;
import org.junit.platform.suite.api.SelectClasses;
import org.junit.platform.suite.api.Suite;


@SelectClasses(CSVFileParserTest.class)
@Suite
public class JunitTestSuite {
}

when running this class using maven no tests are executed, am i missing anything ?

mvn test -Dtest=JunitTestSuite
this is the command i am using to run
HybrisCap
@HybrisCap
hello everyone I'm starting to write some code for the junit tests, I wanted to ask you how do I organize the work for the percentage of class coverage?
where I can find the percentage required for the transition from 6.5.5 to AEM as a Cloud Service
fabb
@fabb
quick questions, since i could not find an answer in my google search: is there a difference in defining multiple @Tag annotations on one class with/without @Tags respectively? if not, why do we need @Tags at all?
2 replies
Jaivignesh-afk
@Jaivignesh-afk
Hi I am Jai Vignesh new to the community,interested in learning junit testing for contributing to open source.It would be really great if anyone could guide to some resources to learn junit tests for jdbc.Thank you.\
Steve Ebersole
@sebersole

I have what I guess is a not common requirement I was hoping to get some thoughts about. It revolves around testing bytecode enhancement - specifically testing the bytecode enhancement Hibernate can apply to an application's domain model.

Ideally I'd like to be able to perform the enhancement as part of the "test infrastruture" - the exact bytecode changes depend on user options. Does JUnit offer a java-agent like capability?

Vikram Deokar
@deokarvikram
I have method like below:

void method{
List<String> grouplist=repo.findDistinctGroup();

for(String group:grouplist){
Student std=new Student();
std.setName("first_name");
std.setGroup(group);
repo.save(std);

}
}

Now I need write the test case in junit to check if save method is successfully required data or not. How can execute the for loop from test method and call the save method?

Vivek Ganesan
@vivganes

Hey folks! I am trying to get a specification of the Junit 5 test report XML. May be an XSD? Can someone please guide me on where to find it?
I have already searched in the github repo of Junit 5 but couldn't find it.

Thanks in advance!

Martin Raedel
@raedma
Hi, just a question regarding an expected behavior of junit5. If I do have two test classes POJOTest and POJOTest2, the tests in POJOTest2 are not executed. Rather it seems, that the complete class is not considered during the test execution with surefire in maven. Is this wanted and expected behavior? I would at least expect a warning that maybe language-wise it is not good practice to have that kind of class-naming with something coming after "Test". Or is this more a surefire problem?
1 reply
Joel Moberg
@joelmo
In an error message, can i print a source code location so the IDE can navigate to the error cause?
Mihály Verhás
@Michael1993
Hi!
This might be a shout into the void but I'm wondering why JavaTimeArgumentConverter implements AnnotationConsumer<A> instead of just implementing ArgumentConverter and extracting the annotation from the ParameterContext
karanshah81295
@karanshah81295

Hi,
We have a test suite which comprises of approx 60 tests and we want to achieve cross browser testing. I have checked multiple resources and found that it can be done by using @TestTemplate and @Parameterized methods. But changing the whole suite and annotate each and every test class or test method results in a lot of code changes. Does junit have any listeners which can modify the TestPlan on runtime or have a configuration xml similar to testng.xml in TestNG.

Any help is much appreciated as we are stuck and need to achieve this at a org level which will require lot of changes if we go the TestTemplate or ParameterizedTest route.

robatxumo
@robatxumo
added the property for a default DisplayNameGenerator and IntelliJ is warning me that it's unused, suggests I remove it, even though it does work?
wasder
@wasder

Hi! I am playing with TestExecutionExceptionHandler. Here is an example:

public class ExceptionSwallowExt implements TestExecutionExceptionHandler {
    @Override
    public void handleTestExecutionException(ExtensionContext context, Throwable throwable) throws Throwable {

        if (throwable instanceof AssertionError) {
            System.out.println("Exception swallowed!");
            return;
        }
        throw throwable;
    }

}
@ExtendWith(ExceptionSwallowExt.class)
public class Example {

    @Test
    void exceptionSwallow() {
        System.out.println("Before exception");
        Assert.assertTrue(false);
        System.out.println("After exception");
    }
}

I want all assertions to be swallowed during test execution and test must be completed fully.
The test actually completes successfully, but stops its' execution at the first exception.

Before exception
Exception swallowed!
BUILD SUCCESSFUL in 5s

I expect the test to continue after first exception. Am I missing something? Is it an expected behaviour or a bug?

Luke Last
@lukelast
Hello! I have a TestExecutionListener with a reportingEntryPublished which works when run from maven, but when running tests from Intellij the reportingEntryPublished method is not being called. Is there any solution to this?
akshaykumar619619
@akshaykumar619619
im unable to understand junit
Torsten Krah
@tkrah
Hi. How can I tell a test method that a specific exception thrown in the body (it needs to be thrown so other handlers of that method actually "see" the exception and can act accordingly - test framework stuff). Using a TestExecutionExceptionHandler does not help because if I swallow that concrete exception there it won't be registered on the ThrowableCollector and "ExtensionContext#getExecutionException()" will be empty as documented on that method. So how can I tell the test method that an instance of exception X is expected and it is still registered in the ExtensionContext so that consumers of that context (springs test framework listeners) still see it and can react on that exception but the test is not failing because of that?
11 replies
Bhargav Choksi
@BhargavChoksi
How to test Redis Time out exception for @Cacheable method with Junit+ Spring integration test?
Vadym
@IakobchukVadym

Hi Junit team.
I have the following configuration for parallel tests execution:

junit.jupiter.execution.parallel.enabled = true
junit.jupiter.execution.parallel.mode.default = same_thread
junit.jupiter.execution.parallel.mode.classes.default = concurrent

So now all my tests classes are executed in parallel and methods in same thread. What I would like to achieve is to execute only 3 test classes from 5 in parallel and other 2 classes in same thread. But I could not find any configuration parameters that will exclude classes from being executed in parallel. Is there any solution for this?

6 replies
Rubens Moreira
@rubensMoreira22

Hello.
I have the following method:
default String mapA ToString (RUBBO rubVO), this method returns a rubVO.codig. "codig" is an attribute of the RUBVO class.

I want to make a test code of this method but I don't know how to check the return of this null.

D3Castro
@D3Castro
Hi! I'm running into some trouble with the jupiter sbt interface. Has anyone else run into any issues with test suites and sbt?
Relevant issue thread: sbt/sbt-jupiter-interface#54
Deep Shah
@Deep201620
   @ExtendWith(MockitoExtension.class)
   public class dmeoStatusServiceTest {

@InjectMocks
DemoService demoService;

@Mock
DemoRepository demoRepository;

@Test
public void shouldDetailedStatus() {
    Optional<Tenant> tenantOptional = Optional.of(createTenantMockObject());
    when(demoRepository.findByMtuNumber("MTU2")).thenReturn(tenantOptional);

    demoService.detailedStatus("Deep Shah", "MTU2");

    verify(demoRepository, times(1)).findByMtuNumber("MTU2");
}
}
I am getting NPE while stubbing the method using Junit5 and Mockito.It works perfect with MockitoJunitRuner
Kyle Aure
@KyleAure
I want to create an extension that sets up services based on enabled tags. Is it possible at runtime to access enabled tags from an extension? If so how would I do that?
3 replies
Eric
@eeverman
Hi - I have a suggestion about the user-guide. Should I submit that as a feature request? My suggestion: The section on Test Execution Order should include a note about the ordering of test methods WRT \@Nested tests. It appears that the test methods of the parent class always run before the \@Nested test methods, but this section doesn't mention that.
Eric
@eeverman

I am trying to create an extension that takes arguments, e.g.

\@Test
\@MyConfigExtension(configFile = "MyFileName")
public void myTest() { . . . run a test ... }

My problem is that if my MyConfigExtension inherits the \@ExtendWith annotation, I don't seem to have anything I can do w/ the parameters I've passed in: ExtendWith only handles a list of classes which JUnit must automatically create instances of. I don't want to inherit from \@RegisterExtensions because I want this to be an annotation on a test method or a test class.

How can I annotate a test method or a test class and pass a parameter to my extension instance?

12 replies
tvmed92
@tvmed92

Hello guys!
Hope here I can find some people with Cucumber+JUnit5 experience.
Me and my team just moved from JUnit4 to JUnit5 and we faced with parallelism issues. With 4th version we used -Dcucumber.options="--threads 5" to run in tests several threads, but after deprecation and removing of cucumber options it's obviously doesn't work anymore. I set up (at least I think so) junit platform engine for the project (https://github.com/cucumber/cucumber-jvm/tree/main/cucumber-junit-platform-engine#configuration-options), but when I try to run tests via comand line (using Gradle task), I receive following error:

UnknownClass.Cucumber > UnknownClass.initializationError FAILED
org.junit.platform.commons.JUnitException at EngineExecutionOrchestrator.java:114
Caused by: org.junit.platform.commons.JUnitException at HierarchicalTestEngine.java:57
Caused by: org.junit.platform.commons.JUnitException at DefaultParallelExecutionConfigurationStrategy.java:41

Unfortunately, didn't find something in the internet, maybe someone can help with it?
What we use:

  • Spring boot 2.7.3
  • Gradle 7.5.1
  • Cucumber java, junit, spring, junit-platform-engine 5.7.0
  • junit-platform-suite-api 1.3.2

Tasks in build.gradle that I have now:
tasks.register<Test>("cucumber") {

useJUnitPlatform()
systemProperty("cucumber.junit-platform.naming-strategy", "long")
systemProperty("cucumber.execution.parallel.enabled", true)
systemProperty("cucumber.execution.parallel.config.strategy", "fixed")
systemProperty("cucumber.plugin", "html:reports/html")
systemProperty("cucumber.plugin", "pretty")
systemProperty("cucumber.plugin", "junit:reports/junit")

doLast {
    javaexec {
        mainClass.set("io.cucumber.core.cli.Main")
        classpath = cucumberRuntime + sourceSets.test.get().output + sourceSets.main.get().output
    }
}

}

tasks {
val consoleLauncherTest by registering(JavaExec::class) {
dependsOn(testClasses)
val reportsDir = file("$buildDir/test-results")
outputs.dir(reportsDir)
classpath = sourceSets["test"].runtimeClasspath
mainClass.set("org.junit.platform.console.ConsoleLauncher")
args("--scan-classpath")
args("--include-engine", "cucumber")
args("--reports-dir", reportsDir)
}

test {
    dependsOn(consoleLauncherTest)
    exclude("**/*")
}

}
Configuration class:

@CucumberContextConfiguration
@Suite
@IncludeEngines("cucumber")
@SelectClasspathResource("com/example")
@ConfigurationParameter(key = GLUE_PROPERTY_NAME, value = "com.example")
@SpringBootTest
@ContextConfiguration(classes = [IntegrationContext::class], loader = SpringBootContextLoader::class)
class Application() {}

uchagani
@uchagani
Is there a way to know if a test is a ParameterizedTest in an extension?
10 replies
Eric
@eeverman

I think there is a documentation error and/or a bug related to the Extension Inheritance section of the User's Manual. Is says:

Furthermore, a specific extension implementation can only be registered once for a given extension context and its parent contexts.
Consequently, any attempt to register a duplicate extension implementation will be ignored.

This is not how extension registration currently works as of 5.9.1. For Programmatic Registration (PR), a new registration is created every time. In other words, every time a field annotated with @RegisterExtension, a registration is created that will receive a set of lifecycle events. That happens even if:

  • The same extension class has already been registered in the test class hierarchy
  • The same extension instance has already been registered in the test class hierarchy

There seems to be no filtering at all on Programmatic registration - here is a test that shows that.

Declarative Registration (DR), however, is ignored if there is a registration for the same extension class anywhere in the test class hierarchy. It doesn't matter if the extension was registration was DR or PR, if the extension class is registered in the hierarchy, DR is ignored (example test).

So, the doc is wrong, but I think this is also a bug or two here. Using PR on an extension instance more than once should be ignored, or perhaps cause an exception. In most (all?) cases it would be unexpected for a single extension instance to receive multiple sets of events.

It also seems like the preferred behavior would be that PR extensions should not block DR extensions. Each PR extension is unique because it can receive unique configuration in its constructor.
A DR extension, however, is distinct from a PR extension of the same class because it is unconfigured: The extension can know from its state that its zero-argument constructor was used and can then
go look for its configuration in annotations. If that is not allowed, then a DR registration on, say, a method can be invisibly broken by some distant superclass.