Add a main method to some classes for simple testing - java

I have some classes throughout a maven project. I would like to add a main method to some of those classes for basic testing while developing.
I tried declaring the class to run with:
mvn exec:java -Dexec.mainClass="huru.util.Async"
but that command looked in my pom.xml file and it ran some pre-configured setup and started my server up as usual. How can I run a specific file (not my regular main class), but still load up the necessary dependencies?
note that for testing I need most of the dependencies in pom.xml, so I will probably need mvn to run the class that I need to test, I can't run it directly with javac.
update sadly, I may need to create a profile in pom.xml since maven can't seem to do very much from the command line. I don't know much about profiles and since I have none in my pom.xml file right now, I am a bit scared of adding that section.

As suggested in the comments, one solution is to skip putting a main method in the class I want to test, but instead create a junit test...this works at the command line:
mvn -Dtest=AsyncTest test
where my test looks like:
package huru;
import huru.util.Async;
import io.vertx.core.Vertx;
import io.vertx.ext.unit.TestContext;
import io.vertx.ext.unit.junit.VertxUnitRunner;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.Arrays;
#RunWith(VertxUnitRunner.class)
public class AsyncTest {
#Test
public void test(TestContext tc) {
Async.Parallel(Arrays.asList(
v -> {
v.done(null, null);
}
), (e, results) -> {
});
}
}

Related

Java Spring boot and Travis CI

I am trying to automatically run my test with Travis CI. I just can't find a good tutorial on how to do this in java. When I push to GitHub I keep getting the following error in Travis :
The command "./mvnw clean install" exited with 127.
My .travis.yml file looks like this:
language: java
jdk:
- openjdk11
script: ./mvnw clean install
This is my Test class
package server;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
#WebMvcTest(CoffeeController.class)
#RunWith(SpringRunner.class)
class CoffeeControllerTest {
#Autowired
private MockMvc mockMvc;
#Test
void getAllCoffee() {
try {
mockMvc.perform(get("/coffee/all")).andExpect(status().isOk());
} catch (Exception e) {
e.printStackTrace();
}
}
}
I searched several tutorials on Youtube and on the web but I can't seem to get the answer. I hope any of you can help me. I appreciate it very much! I also tried to remove the script but also no success.
The return code 127 is telling you that it cannot find the command. In this case mvnw.
Please take a look, that your mvnw (mvn wrapper) is in the PATH, or try the absolute path. Also the mvnw should be part of the project, if it isn't pushed you can push it, or use a openjdk with mvn to build your app.
It works for me:
sudo: required
language: java
before_install:
- mvn clean install
I think you should change the script value to this:
script: ./mvn clean install
I'm not sure but you could try it

NoClassDefFoundError: org/apache/nifi/registry/VariableRegistry while running nifi test cases

I am pretty much new to apache nifi. Couple of days back I stuck at this problem (which involves miss behaving custom nifi processor). Debugging wasnt helping me well. So I decided to explore nifi mock framework (which I should be doing already, but didnt do it :) as suggested in comments on that question.
I am taking help from these links: 1, 2
What I was trying to do is to send single flow file to custom processor. For that I saved/serialized actual flow file using MergeContent (with FlowFile v3 version) and PutFile processor as suggested here. Now I am trying to re-read this file through code in my test using GetFile processor as follows:
import static org.junit.Assert.*;
import java.util.List;
import org.junit.Test;
import org.apache.nifi.util.TestRunners;
import org.apache.nifi.processors.standard.GetFile;
import org.apache.nifi.util.MockFlowFile;
import org.apache.nifi.util.TestRunner;
public class MyCustomProcessorTest {
#Test
public void testOnTrigger() {
TestRunner runner = TestRunners.newTestRunner(new GetFile());
runner.setProperty(GetFile.DIRECTORY, "C:\\Mahesh\\delete\\serialized-flow-files");
runner.setProperty(GetFile.KEEP_SOURCE_FILE, "true");
runner.run(1);
List<MockFlowFile> results = runner.getFlowFilesForRelationship(GetFile.REL_SUCCESS);
System.out.println("done");
}
}
This is giving me following error:
Which maven dependency should I include to get this class? Also is my approach fine or there is any more preferable approach?
I would double-check if org.apache.nifi:nifi-api: is in the classpath.
If using maven I would run
"mvn dependency:tree" to check.

How to only run tests in a TestSuite class with gradle wrapper command

I have a testSuite class:
package com.company.tests;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import com.company.tests.facing.CustomerTests;
import com.company.tests.backend.BookTests;
import com.company.tests.backend.ChargeTests;
#RunWith(Suite.class)
#Suite.SuiteClasses({
CustomerTests.class,
BookTests.class,
ChargeTests.class,
})
public class TestSuite {
}
I use a gradle wrapper to run the tests as follows:
./gradlew test -PTestSuite
...but this runs ALL tests under /src/test/java/com/company/tests/
Is there a way I can run JUST the ones in TestSuite class using gradle wrapper from commandline? I looked at other questions on stackoverflow but couldn't work out, Please give an example.
This can be achieved by running the following:
./gradlew test --tests TestSuite
And the documentation provides information about the kind of matching it supports.
Note that this assumes Gradle 4.7+.

Netbean is opening Junit3 template instead of Junit4

I'm Using Netbean for Java Assignment (for School) and doing Unit Test (JUnit) yesterday.
When i added New > JUnit Class, it used to open Java Class starts with ...
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
public class UtilsClass {
...
}
But Today When i add New > JUnit Class. it opens Java Class starts with
import junit.framework.TestCase;
public class NewEmptyJUnitTest1 extends TestCase {
.....
}
i know both are Junit Class but i really want back the 1st one as i'm used to it. i have done complete uninstallation of Netbean and reinstall it.
Ok it's an old question but since I had the same problem right now, I think it is worth an answer. Maybe it is also useful for others.
I observed that if I create a new plain project in NetBeans, create a class and create a test class from it by right clicking the class -> Tools -> Create/Update Test, a JUnit4 test class is created. This leads me to the following solution:
Ensure that you have the correct library included in your project's TestLibraries folder, if not right click the TestLibraries folder, remove the JUnit3 library and replace it with the JUnit4 library, which you can download here: https://junit.org/junit4/.
(note that JUnit4.12 has a dependency on the hamcrest 1.3 library, anyway both libraries are already present in the NetBeans 8.2 installation)
Asuming that you already had the correct libraries included and the problem still exists, as it was for me. You can check the NetBeans project properties file <NetBeans-Project-Location>/nbproject/project.properties. Within this file you may find the property junit.selected.version=3 you can eigther change this to 4 or delete the whole line.
Save the file. If you now create a test class the JUnit4 tamplate will be picked.
Enjoy writing your JUnit4 tests. ;)

Run all tests in Junit 4

I want to be able to run all tests in a project programmatically. I know Eclipse has a "Run as JUnit test" configuration which somehow grabs all the tests in a project and run them. Is there any way for me to also grab the list of tests programmatically and run them? Or is there some good way to construct a test suite containing all the test cases without manually listing out every one (all 700+) of them?
I've tried the "New... -> Test Suite" option in Eclipse, but that seems to work only for JUnit 3, identifying tests by their extending from TestCase
The test classes are JUnit 4, so their only distinguishing characteristic is the annotation, no naming convention, no subclassing from TestCase.
Thanks in advance!
Though it does not really solve your immediate problem, I find it a very useful general practice to create suites and suites of suites, e.g. for a package something like PackageFooSuite etc. and assemble these suites in one or more suites again, like ModuleFooSuite and have one top-level suite, like AllTestsSuite. That way it's easy to run both all tests in one step as well as submodule tests for the package I'm currently working on (and have the tests run quicker than if I would always run all of them):
#RunWith(Suite.class)
#Suite.SuiteClasses({ PackageFooSuite.class, PackageBarSuite.class} )
public final class AllTestsSuite {} // or ModuleFooSuite, and that in AllTests
None of the other answers did it for me. I had 40k tests I needed to run, so manually listing every class was not an option.
I did it with ClasspathSuite. A test suite that runs all Junit4 and Junit3 test cases in the class path is as follows:
import org.junit.extensions.cpsuite.ClasspathSuite;
import org.junit.extensions.cpsuite.ClasspathSuite.*;
import org.junit.runner.RunWith;
import org.junit.runner.JUnitCore;
import static org.junit.extensions.cpsuite.SuiteType.*;
#RunWith(ClasspathSuite.class)
#SuiteTypes({ JUNIT38_TEST_CLASSES, TEST_CLASSES })
public class RunAllSuite {
/* main method not needed, but I use it to run the tests */
public static void main(String args[]) {
JUnitCore.runClasses(RunAllSuite.class);
}
}
I needed to run it from command line, so this is what I did:
Downloaded cp-1.2.6.jar
Create the previously mentioned RunAllSuite
Compile the class, javac RunAllSuite.java -cp cpsuite-1.2.6.jar;junit-4.8.1.jar
run it with target tests in the class path, java -cp cpsuite-1.2.6.jar;junit-4.8.1.jar;path/to/runallsuite/folder;target/classes;target/test-classes RunAllSuite
And that's it. With the RunAllSuite above, anywhere in your code you can just do JUnitCore.runClasses(RunAllSuite.class), which runs all tests in class path. There are other config options as well which are explained in the ClasspathSuite home page.
Note also that the class given above does not print anything. If that is needed, you can do
import org.junit.extensions.cpsuite.ClasspathSuite;
import org.junit.extensions.cpsuite.ClasspathSuite.*;
import org.junit.runner.RunWith;
import org.junit.runner.JUnitCore;
import org.junit.internal.TextListener;
import static org.junit.extensions.cpsuite.SuiteType.*;
#RunWith(ClasspathSuite.class)
#SuiteTypes({ JUNIT38_TEST_CLASSES, TEST_CLASSES })
public class RunAllSuite {
public static void main(String args[]) {
JUnitCore junit = new JUnitCore();
junit.addListener(new TextListener(System.out));
junit.run(RunAllSuite.class);
}
}
You can do this fairly easily from within maven using the surefire plugin: I usually clean/compile/install my projects from the command line before comparing them for eclipse usage (mvn eclipse:clean eclipse:eclipse) and you can define a test suite in your pom which lists all the tests you want to run en masse every time you run mvn install. You're not calling them programatically, exactly, but you can certainly call them en masse.
In Eclipse (I'm using 4.6.1) - Right click the project folder, select "Run As", choose "JUnit Test"
It will run all tests in that project. Same for a package.
Of the top of my head using Spring:
Implement a TypeFilter that matches classes with methods annotated with #Test (don't forget to consider the superclasses)
Invoke classpath scanning on your top-most test package
Invoke the JUnitRunner with the scan results
More info on classpath scanning and custom type filters here
With Eclipse Indigo (possibly Helios as well) in the Run Configurations dialog box, you now have the ability to Run all tests in a selected project, package or source folder.
Also a good reference from Eclipse is the article Java Unit testing with JUnit 4.x in Eclipse.
I also recommend using the JUnit Suite annotations. Follow the link for more detail.

Categories