I have Junit5Runner class which starts Junit5 test programmatically.
It's not a maven project now, it's a simple java project with no any framework.
I need to switch to maven project, but in a maven project test classes are located inside test folder and aren't accessable from src folder.
How can I get access to test class from test folder in the main class from src folder?
Here is my Junit5Runner code.
Here I get access to CalculatorTest class.
public class Junit5Runner {
SummaryGeneratingListener listener = new SummaryGeneratingListener();
public void runOne() {
LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder.request()
.selectors(selectClass(CalculatorTest.class)) //I NEED TO GET THIS CLASS FROM TEST FOLDER
.build();
Launcher launcher = LauncherFactory.create();
TestPlan testPlan = launcher.discover(request);
launcher.registerTestExecutionListeners(listener);
launcher.execute(request);
}
public static void main(String[] args) {
final Junit5Runner runner = new Junit5Runner();
runner.runOne();
TestExecutionSummary summary = runner.listener.getSummary();
for (TestExecutionSummary.Failure failure : summary.getFailures()) {
System.out.println(failure.getTestIdentifier().getDisplayName());
System.out.println(failure.getException());
}
}
}
The simplest solution is to put your production code int src/main/java/<package> and your unit tests into src/test/java/<packageName> and name your unit tests like *Test.java. If you follow that you can execute your unit tests (assumed you have added the appropriate dependencies for JUnit Jupiter in your pom file) via
mvn clean test
Full setup for JUnit Jupiter and example project can be found here.
Related
I have JUnit tests located in different test folders, when I'm running them one by one everything is green all tests are passed in particular folder, but when its done in scope (all at once), some tests are failing due to some data is changed during previous tests execution. So it's a way to run JUnit tests from scratch, I've tried
mvn "-Dtest=TestClass1,TestClass2" test
but some tests are failed. When its done like:
mvn "-Dtest=TestClass1" test
all passed. Or when:
`mvn "-Dtest=TestClass2" test
all passed.
As long as TestClass1 and TestClass2 share common state there might be no way to run them together e.g. it could be a static field somewhere in the JVM. You must refactor the tests so they are isolated and have no side effects e.g. use #Before and #After to clean up resources after the test.
You could play with Maven Surefire Plugin options to spawn a new JVM for each test but it would be very inefficient.
For this specific problem, you can create a TestSuite.
Create Two Test Suite Classes
Attach #RunWith(Suite.class) Annotation with the class.
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
#RunWith(Suite.class)
#Suite.SuiteClasses({
TestJunit1.class
})
public class JunitTestSuite1 {
}
#RunWith(Suite.class)
#Suite.SuiteClasses({
TestJunit2.class
})
public class JunitTestSuite2 {
}
public class TestRunner {
public static void main(String[] args) {
Result result1 = JUnitCore.runClasses(JunitTestSuite1.class);
Result result2 = JUnitCore.runClasses(JunitTestSuite2.class);
for (Failure failure : result1.getFailures()) {
System.out.println(failure.toString());
}
for (Failure failure : result2.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(result1.wasSuccessful());
System.out.println(result2.wasSuccessful());
}
}
Consider this code GitHub: Spring Pattern Example Code
If you checkout Chapter3 - Dependency Injection, the project does not have any main class in it.
I did a
mvn clean install
which was successful.
When I go to execute the jar, I get the below error:
bash-3.2$ java -jar
./target/Chapter-03-Spring-Dependency-Injection-0.0.1-SNAPSHOT.jar
no
main manifest attribute, in
./target/Chapter-03-Spring-Dependency-Injection-0.0.1-SNAPSHOT.jar
How can I run this project? Should I edit the build portion of pom to build as spring-boot? Should I manually add a MANIFEST file?
Its not a complete application that you could run, so you must type some lines to see what's going on , here is what you could do to run examples :
import project into your IDE as maven project
create Main class with famous static main
if you want to instantiate the config with xml style you could do it as follow
public class Main {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
TransferService bean = context.getBean(TransferService.class);
bean.transferAmmount(10l, 10l, new Amount(1000d));
}
}
Another approach is to use config file :
public class Main {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
TransferService bean = context.getBean(TransferService.class);
bean.transferAmmount(10l, 10l, new Amount(1000d));
}
}
run the project as java application
I want to run a simple TestNG class using terminal not after adding it in suite.xml
I want to invoke the eclipse operation Right click -> Run As -> TestNG Test using terminal/CLI.
Is there is any way to Do it?
public class FirstTest {
#Test()
public void test {
System.out.println("Hello TesNG!");
}
How to compile and Run the above TestNG code using CLI?
There's no direct way to do this according to the docs - you need to specify an xml suite in order to use the testNg CLI like java org.testng.TestNG testng1.xml
However, you can create some main method in your project and invoke TestNg programmatically: add necessary Test classes into suite and call this main method from CLI like any other Java application:
public static void main(String ... args){
TestListenerAdapter tla = new TestListenerAdapter();
TestNG testng = new TestNG();
testng.setTestClasses(new Class[] { FirstTest.class });
testng.addListener(tla);
testng.run();
}
And then in command line:
javac some.package.your.MainClass.java
java some.package.your.MainClass
I have a question regarding unit testing of jsonschema2pojo.
What I am trying to do is use the sample unit test in https://github.com/joelittlejohn/jsonschema2pojo/blob/master/jsonschema2pojo-integration-tests/src/test/java/org/jsonschema2pojo/integration/json/RealJsonExamplesIT.java
to set up my own test, however I find that there is no test library available. I tried to set up the sources in my project, but I am not using Maven, but Gradle. For the lack of Maven, the class or.jsonschema2pojo.integration.util.JsonSchema2PojoRule class does not want to compile without Maven in my project. In our team we do not use maven in our build server.
I hope that someone can help me point in the direction of how I would unit test my implementation method.
This is the unit test I am trying to run:
public class AnalyticsGeneratorImplTest extends AbstractGoogleAnalyticsTest {
// Set a logger
private static Logger log = LoggerFactory.getLogger(AnalyticsGeneratorImplTest.class);
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
#Rule
public JsonSchema2PojoRule schemaRule = new JsonSchema2PojoRule();
#Test
public void getTitleFromGeneratedJson() throws Exception {
//verify that the incoming Json has been transformed
ClassLoader resultsClassLoader = schemaRule.generateAndCompile("/assets/generated-list/google-analytics.json", "uk.ac.soton.generators.analytics.target",
config("sourceType", "json",
"useLongIntegers", true));
Class<?> googleAnalyticsJsonObject = resultsClassLoader.loadClass("uk.ac.soton.generators.analytics.serialised.GoogleAnalyticsJsonObject");
Object gaJsonObj = OBJECT_MAPPER.readValue(this.getClass().getResourceAsStream("/assets/generated-list/google-analytics.json"), googleAnalyticsJsonObject);
Object result = googleAnalyticsJsonObject.getMethod("getResult").invoke(gaJsonObj);
Object data = result.getClass().getMethod("getData").invoke(result);
Object title = data.getClass().getMethod("getTitle").invoke(data);
assertThat(title.getClass().getMethod("getTitle").invoke(title).toString(), is("blue"));
}
}
You need add the dependecies in gradle:
compile group: 'org.jsonschema2pojo', name: 'jsonschema2pojo-gradle-plugin', version: '0.4.29'
And the others one. If there exist in Maven, it can exist in Gradle too. Check in MavenRepository and select the dependecie you want and Will be exist for all Java Build Toll just select the Gradle Tab and you see the dependecie you need. org.jsonschema2pojo
I want to create simple java project with JUnit, so for example I'm want to write an algorithm like merge sort or some Java class and create test class so I can make unit test for that class.
I've create the project with:
File -> New -> Project -> java -> next and setup the project name and
location
and I want to make the unit test for the class the I've created, and I've tried the following solotions :
solution 1 from IntelliJ IDEA dosc using the light bulb to create the test class
solution 2 using shortcut [ctrl + shift + t]
But I always endup with import static org.junit.Assert.*; cannot resolve symbol 'junit', I tried different unit test library end up the same way.
How to resolve this problem so I can make unit test class in this simple Java project?
You can use Gradle or Maven (my personal preference these days).
But the easiest way is to add the JUnit JAR to your project, write some tests, and execute them in IntelliJ.
Go to JUnit and download version 4.12 of the JAR. Put it in a folder /test-lib in your IntelliJ project.
Create a folder /src and add a package /model and a Java class Foo to it (I'll write you one).
Mark /src as a source root.
Create a folder /test and add a package /model and a Java class FooTest to it (I'll write that, too).
Mark /test as a test source root.
Right click on /test and tell IntelliJ to "Run All Tests".
IntelliJ will run all the tests and present the results in the Run window.
Here's the model class:
package model;
public class Foo {
private String value;
public Foo(String v) { this.value = v; }
public String toString() { return this.value; }
}
Here's the test class:
package model;
public class FooTest {
#Test
public void testToString() {
String expected = "Test";
Foo foo = new Foo(expected);
Assert.assertEquals(expected, foo.toString());
}
}
I'm not sure this is the best solutions but I manage to build the unit test use gradle and maven. like this :
create Java project :
File -> New -> Project -> Gradle -> choose only java-> fill the
groupId and ArtifactId-> choose use default gradle wrapper -> enter
project name and location ->finish
and from the root of the project
right click -> Add Framework Support -> choose maven.
from there I can create the class that I want and make the unit test using the solutions from the question [ctrl + shift +t] .