Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Repo info
Activity
  • 12:23
    codecov[bot] commented #2785
  • 12:17
    codecov[bot] commented #2785
  • 12:17
    codecov[bot] commented #2785
  • 12:16
    hglasgow synchronize #2785
  • 11:57
    codecov[bot] commented #2785
  • 11:48
    codecov[bot] commented #2785
  • 11:48
    codecov[bot] commented #2785
  • 11:47
    hglasgow synchronize #2785
  • 11:36
    codecov[bot] commented #2785
  • 11:36
    codecov[bot] commented #2785
  • 11:35
    hglasgow synchronize #2785
  • 08:55
    sbrannen labeled #2787
  • 08:55
    sbrannen labeled #2787
  • 08:54
    sbrannen commented #2787
  • 08:54
    sbrannen edited #2787
  • 08:53
    sbrannen edited #2787
  • Dec 05 21:46
    github-actions[bot] labeled #2787
  • Dec 05 21:45
    klease opened #2787
  • Dec 05 19:35
    chenrui333 opened #157
  • Dec 05 19:22
    chenrui333 commented #155
Jonathan Bluett-Duncan
@jbduncan
Regardless, the JUnit 5 team have not been looking at messages here for quite a while, so I suggest raising an issue.
Leo Tietz
@Quicksteve
Okay, thanks. I'll create an issue then.
Maiko Cunha
@mkacunha

Hello,

I was working in a project where I’ve had the needs when I’ve created a parameterized test with the annotation @ParameterizedTest and @CsvFileSource, my need was that I would like to have the possibility to choose different csv file by profile, e.g.: when profile is equals prod, I would like run the test with file-prod.csv and when the profile was dev I’d like to run the test with file-dev.csv. So I did a custom annotation for me to use in the test, and I’d like to know if it would be interesting to create a feature request issue on Github. Bellow the code and an example:

Annotation:

@Target(
            AnnotationTarget.ANNOTATION_CLASS,
            AnnotationTarget.FUNCTION,
            AnnotationTarget.PROPERTY_GETTER,
            AnnotationTarget.PROPERTY_SETTER
        )
        @kotlin.annotation.Retention(AnnotationRetention.RUNTIME)
        @MustBeDocumented
        @API(status = API.Status.STABLE, since = "5.7")
        @ArgumentsSource(
            CsvFileSourceByProfileProvider::class
        )
        annotation class CsvFileSourceByProfile(
            val resources: Array<String> = [],
            val delimiter: String = ""
        )

Provider:

        class CsvFileSourceByProfileProvider : ArgumentsProvider, AnnotationConsumer<CsvFileSourceByProfile> {
            private lateinit var csvParser: CsvParser
            private lateinit var resources: Array<String>

            override fun provideArguments(context: ExtensionContext?): Stream<out Arguments> {
                return this.resources
                    .map(this::readResource)
                    .flatten()
                    .stream()
            }

            private fun readResource(resource: String): List<Arguments> {
                val resourceAsStream = this.javaClass.getResourceAsStream(resource)
                    ?: throw IllegalArgumentException("Resource $resource not found")

                val bufferedReader = BufferedReader(InputStreamReader(resourceAsStream))
                csvParser.beginParsing(bufferedReader)
                val arguments = csvParser.parseAllRecords().map { Arguments.arguments(*it.values) }

                bufferedReader.close()

                return arguments
            }

            override fun accept(annotation: CsvFileSourceByProfile) {
                validateInputs(annotation)

                val csvParserSettings = CsvParserSettings()
                csvParserSettings.format.delimiter = annotation.delimiter.single()
                csvParser = CsvParser(csvParserSettings)

                val profiles: Array<String>? = SystemPropertiesUtil.getActiveProfiles()
                val resourcesReplaced = annotation.resources.map { it.replace(".csv", "") }.toTypedArray()


                if (profiles == null || profiles.isEmpty()) {
                    throw IllegalArgumentException("It wasn't possible define profile, profile must be enter by parameter, e.g.: ‘-Dspring.profiles.active=qa’")
                }

                this.resources = profiles
                    .map { profile ->
                        resourcesReplaced.map { resource -> "$resource-$profile.csv" }
                            .map { if (it.startsWith("/")) it else "/$it" }
                    }
                    .flatten()
                    .toTypedArray()
            }

            private fun validateInputs(annotation: CsvFileSourceByProfile) {
                if (annotation.delimiter.isBlank()) {
                    throw IllegalArgumentException("Delimiter must not be empty in @CsvFileSourceByProfile")
                }

                if (annotation.resources.isEmpty()) {
                    throw IllegalArgumentException("Resources must not be empty in @CsvFileSourceByProfile")
                }
            }
        }
Example code:
@ParameterizedTest
    @CsvFileSourceByProfile(resources = ["/file-one.csv", "file-two", "file-three"], delimiter = ";")
    fun testTwo(num1: Int, num2: Int, num3: Int) {
        println("$num1 - $num2 - $num3")
    }
uchagani
@uchagani
I know this has been brought up in the past but what are the chances of getting conditional loading of extensions? For example, I have a set of extensions that interact with BrowserStack (connecting, sending test status, etc) but I only want these extensions to load when I’m running against browserstack. Currently this is triggered by a system property.
Maiko Cunha
@mkacunha
Hello, thank you for answering me, I don’t know if I understand you, but my case was that I had many test and I had to run the tests in different environments and each environments different input data, in this case that you talked about, it seems that could be solved with annotation as @Profile from own spring, or another framework that has this kinda annotation, or could be use @EnableIf from JUnit.
Orsák Maroš
@see-quick
Hi guys, before I write the question regarding to parallel execution...this is right chat to ask? ... or you use different room, chat etc?
Orsák Maroš
@see-quick
Hmmmm :D
Steve Ebersole
@sebersole
I have a requirement I was wondering whether JUnit 5 can handle... I need to be able to bytecode transform classes used within a test.
Steve Ebersole
@sebersole
similar to applying an agent to specific tests
Steve Ebersole
@sebersole
for background, when running Hibernate tests certain tests test our bytecode enhancement of entities, etc. It would be best if we could perform dynamic enhancement as those classes are loaded. Which is what I am trying to figure out
Steve Ebersole
@sebersole
Bueller?
Steve Ebersole
@sebersole
FWIW we use a dedicated Runner for this in some JUnit 4 based tests. But Runner ofc is not supported in JUnit 5
harpreet86
@harpreet86
Hi, I want to migrate my project from JUnit 4 to JUnit5, please suggest with migration guide if any. Also my existing code use PowerMock extensively and I am not able to find any support for PowerMock with JUnit 5, please suggest.
Karl Heinz Marbaise
@khmarbaise
First I would suggest to take a look into the documentation https://junit.org/junit5/docs/current/user-guide/#migrating-from-junit4 apart from that I would really ask why do you need Powermock? My opinion is: Using powermock means having issues in your code..Usually Mockito is more than sufficient...
harpreet86
@harpreet86
PowerMock is used to mock static classes etc. and it is heavily used so may be migration will become overhead
Karl Heinz Marbaise
@khmarbaise
I know why PowerMock is used ... but static classes/static methods etc. Apart from that Mockito supports static methods. But the question is is the code which needs powermock (static classes) for testing is in a good shape... (My opinion).. let us start with a concrete example... can you give an example of your test where you need PowerMock... maybe find a solution with JUnit Jupiter...?
harpreet86
@harpreet86
I mean I mentioned usage of PowerMockito in context of my project. Let me isolate one example from my project.
harpreet86
@harpreet86

Code for My class:

import org.slf4j.LoggerFactory;

public class Logger {
private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(Logger.class);

public void test() {
    LOGGER.info("this method is yet not implemented.");
}

}

Test Class for the above Class:

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.slf4j.LoggerFactory;

@RunWith(PowerMockRunner.class)
@PrepareForTest({LoggerFactory.class})
@PowerMockIgnore("jdk.internal.reflect.*")
public class TestLogger {
private static org.slf4j.Logger LOGGER;

private Logger objectUnderTest;

@Before
public void setUp() {

    LOGGER = PowerMockito.mock(org.slf4j.Logger.class);
    PowerMockito.mockStatic(LoggerFactory.class);
    PowerMockito.when(LoggerFactory.getLogger(Logger.class))
          .thenReturn(LOGGER);

    objectUnderTest = new Logger();
}

@Test
public void validateTest() {
    objectUnderTest.test();
    Mockito.verify(LOGGER).info("this method is yet not implemented.");
}

}

harpreet86
@harpreet86
Please suggest.
Pavel Jandejsek
@paveljandejsek
Hello everyone, may I ask what is the recommendation for Extension support in custom TestEngine? Since extensions come from junit-jupiter-api (and not platform) is it a bad idea to try and support them in custom engines? (And is there some easy way to do that?)
I am writing a custom engine and it might be really nice to easily reuse some extensions like TestcontainersExtension for Jupiter, but on the other hand I am wondering if what I am contemplating isn't a bad idea for some reason... Is there some recommendation about this?
Sergio Freire
@bitcoder
Hi everyone, good morning :) Do you have insights on JUnit4 vs JUnit5 usage statistics? Is Junit4 (the old project) still used a lot?
Ed Gonzales
@edgonzales
@bitcoder Maybe one way to find out is how many times each has been forked in Github?
Sergio Freire
@bitcoder
I also looked at maven repo statistics, namely on the dependencies
@edgonzales , that's a good idea
Ed Gonzales
@edgonzales
Cool beans, glad it worked out.
Sergio Freire
@bitcoder
any ideas on why a team would decide to stick with JUnit4? just because of the effort that it would require to upgrade? any thoughts? :)
Orsák Maroš
@see-quick
currently, I am playing with the junit5 parallelism experimental feature. I have got few questions regarding this:
  1. Am I able to run 4 methods in parallel 2 classes in parallel? In other words is there some configuration that I can explicitly specify? Currently, I can do this junit.jupiter.execution.parallel.config.fixed.parallelism=20, which will run 20 methods (test cases) in parallel.
  2. Is there some similar @Isolation annotation for classes? The main purpose why do I need this is sometimes you execute test cases, which are needed to run in isolation but with @Isolation annotation, you could do this only in method scope.
  3. As a user, can I access some metadata info about current running tests and so on? (this is basically handled by Junit5 engine). I know about ExtensionContex or TestInfo classes but this one provides static info about test cases. (I need dynamic metadata info about whole scope of execution)
Peter Schaeffer
@pschaeffer
Hi, this is just a test

I have a problem using Junit tests with Java and Eclipse. All of my tests run just fine when I invoke them standalone. By this I mean that HDLmTreeTest, HDLmTreeTest1, and HDLmTreeTest2 all run fine when I run them by themselves. However, I have a Java source module with all of the test files in it. See below.

package com.headlamp;
import org.junit.platform.runner.JUnitPlatform;
import org.junit.platform.suite.api.SelectClasses;
import org.junit.runner.RunWith;
@RunWith(JUnitPlatform.class)
@SelectClasses({HDLmConfigTest.class, HDLmDefinesTest.class,
HDLmErrorTest.class, HDLmStringTest.class, HDLmTreeTest.class,
HDLmTreeTest1.class, HDLmTreeTest2.class,
HDLmModTest.class, HDLmBuildJSTest.class, HDLmFindTest.class,
HDLmAssertTest.class, HDLmBuildLinesTest.class, HDLmUtilityTest.class,
HDLmSavedChangeTest.class, HDLmCurlApacheTest.class, HDLmMainTest.class,
HDLmJettyTest.class, HDLmCurlJettyTest.class, HDLmEditorServletTest.class,
HDLmApacheTest.class, HDLmProxyTest.class, HDLmSessionTest.class,
HDLmLogMsgTest.class, HDLmMatchTest.class, HDLmImageInformationTest.class,
HDLmClusteringTest.class, HDLmJsonTest.class})
class HDLmAllTests { }

When I run this file, all of my tests get invoked except for HDLmTreeTest1.class and HDLmTreeTest2.class. I should say that HDLmTreeTest1.class and HDLmTreeTest2.class were just recently created and added to the SelectClasses list. For some reason, they are not invoked, but all of the other classes are invoked. What am I doing wrong?

2 replies
Peter Schaeffer
@pschaeffer
I figured this out (with lots of online help). The problem was the name(s) of my test classes. Test classes (the names of test classes) must end with 'Test' or 'Tests'. They can not end with 'Test1' or 'Test2'. That was my error. I changed the class names and the problem went away. See https://howtodoinjava.com/junit5/junit5-test-suites-examples/ for some details.
@jbduncan I figured this out (with lots of online help). The problem was the name(s) of my test classes. Test classes (the names of test classes) must end with 'Test' or 'Tests'. They can not end with 'Test1' or 'Test2'. That was my error. I changed the class names and the problem went away. See https://howtodoinjava.com/junit5/junit5-test-suites-examples/ for some details.
Eirik
@emyklebost
This message was deleted
Loic Rutabana
@zurulo03:matrix.org
[m]
This may not be a JUnit issue but when I testing out a method using a JUnit test class, and instantiating an object of the class that I'm trying to test, it doesn't seem to run the code in the constructor. I declare a new instance of Random (called it rand) in the field an instantiated it in the constructor (of the class I'm testing) and it says that rand is null when running testing the method (which uses rand)
I'm using JUnit5 by the way
Suhas Valanjoo
@suhasw_twitter
Hi all, I am looking for good example code for JUnit5 and Mockito. Are there any repositories on Github that you would recommend? Thanks in advance!
alexeev509
@alexeev509
Hi all! I have complicated question: Can PostDiscoveryFilter filter parametrized test cases of JUnit5? For example i have parametrized test-case and i want to filter out this test-case only with second param; I realized this idea with JUnit4, but have difficulties with JUnit5; More details (with snippets of code) of my issue are published on StackOverflow: https://stackoverflow.com/questions/69305405/can-postdiscoveryfilter-filter-parametrized-test-cases-of-junit5
Pawan Pandit
@meet_pawan53_twitter
Hi All,
Can any one help me to configure the JUnit 4 for eclips ,
Tamás Szabó
@GethDeeo

Hi,

I've a fairly large number of webapp functional tests on this stack: junit4(+suites) + spock1. It's working nicely thanks to the parallel suite execution (class level parallelization and forking are not options).
I've tried to upgrade to junit5(+suites) + spock2, but hit a wall, because it seems to me that currently top level of parallelization is class (spock spec), I need Spock, but 2.0 is tied to Junit5 only.
Am I missing something, and if not, are there plans to support this scenario?

e-ts
@e-ts

Hello friends. I just noticed the POM on Central for junit-jupiter-api:5.7.2 depends on apiguardian-api:1.1.0 while the source code on r5.7.2 declares version 1.1.1. Do you know why?

https://search.maven.org/artifact/org.junit.jupiter/junit-jupiter-api/5.7.2/jar
https://github.com/junit-team/junit5/blob/r5.7.2/gradle/libs.versions.toml

Patrick
@munichbughunter

Hello,
is it possible to run @ParameterizedTest via Console Launcher?

Actual I have the following problem.
@ParameterizedTest(name="Awesome Test") @ArgumentsSource(AwesomeDataArgumentsProvider.class) void myAwesomeTest(final AwesomeData awesomeData) { System.out.println(awesomeData); }

I call the console executor in this way - in the options is the right package, class and method defined like this (de.awesome.AwesomeTestClass#myAwesomeTest):
testExecutionSummary = Optional.ofNullable(new ConsoleTestExecutor(options).execute(new PrintWriter(System.out)));

And then I get the following error:

TestEngine with ID 'junit-jupiter' failed to discover tests
Could not find method with name [myAwesomeTest] in class [de.awesome.AwesomeTestClass]

When I change the Annotation to @Test than everything is working...
Any idea what is wrong or is it not possible?

GianniGiglio
@GianniGiglio
Hi,
Question: Am trying to run some test using junit5 suite-api and engine. However, my test are executed twice. Once by the suite and once for the test class. How do I prevent this ?
Steve Ebersole
@sebersole
I seem to have lost the reference to an issue I have been waiting for 5.8 to resolve. I just noticed y'all are up to 5.8.1 and wanted to find out the status. Even just a link to docs for it or the issue would be great. It had to do with using parameter resolution as part of a custom extension. I have an extension which supports methods annotated with a custom @OnFailure annotation, but those methods need access to a parameter resolver supplied by another extension.
found it... junit-team/junit5#2393 so apparently this has now been pushed to 5.9 :(
Aman Sharma
@algomaster99

Hi! I had question about running scripts using Junit 5. I have the following piece of code:

public class RunMvnSubprocess {
    @Test
    public void main() throws IOException, InterruptedException {
        String[] cmd = new String[]{"mvn.cmd", "-version"};
        Process p = Runtime.getRuntime().exec(cmd);
        try (BufferedReader output = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
            String line;
            while ((line = output.readLine()) != null) {
                System.out.println(line);
            }
        }
        p.waitFor();
    }
}

I get no output when I run it using Junit 5. However, running this on Junit 4 works fine.

Please note that I am running this piece of test in Windows 10.

Jared Komoroski
@JKomoroski

Does anyone know how test containers might differ between surefire, failsafe, and intellij?

I'm having an issue with an afterAllcallback that runs fine when maven failsafe invokes the test, but when I run all the tests in intellij, the after all step is called between each class.

1 reply
artemryazantsev
@artemryazantsev
Hey there!
Could somebody help how to achieve such type of parallel executiion via Junit5 + Selenium 4+?
            'junit.jupiter.execution.parallel.enabled'                 : true,
            'junit.jupiter.execution.parallel.mode.default'            : 'concurrent',
            'junit.jupiter.execution.parallel.mode.classes.default'    : 'concurrent',
            'junit.jupiter.execution.parallel.config.strategy'         : 'fixed',
            'junit.jupiter.execution.parallel.config.fixed.parallelism': 10,
            'junit.jupiter.extensions.autodetection.enabled'           : true,
I tried to implement CustomStrategy, but can't achive this mixed (classes+methods) parallelism
I've followed this issue - SeleniumHQ/selenium#9359