Running testing class from jar package in NetBeans - java

I have like 30 Java classes and 1 class for testing in a jar package.
To run the testing class, I need to create new NetBeans project , import all those 30 classes into /src , then import 1 testing class into /test and maybe add some libraries to the project also...
So that, after all I will be able to run the testing class...
Is there some other way to do it?
I open the jar package in NetBeans and see all the classes but it doesn't let me run the testing class since there is no main method in there..

A bunch of ways. If you're in NetBeans, and the class has a public static void main() method you can just right-click it and choose Run File.
But you're far better off writing your test as a JUnit or TestNG test - that way it is not included in your production bits, and continuous build tools and other things will be able to run your tests automatically because they look the way those tools expect.

Related

Unable to run JUnit test in IntelliJ

I wanted to start project using TDD. Created the test directory and later changed it to package that is integrated with src direcotry. In both cases I get the same error:
Class not found: "tests.objectsTest"
I tried different techniques of importing JUnit jar and none solved problem. Also I tried to rename my test class but it gives no solutons whatsoever.
It seems that IntelliJ or JUnit changes name of the test class. Shouldn't it be objectsTest.tests?
I am using JUnit version 4.12 and latest IntelliJ EAP.
This is my project structure:
Project:
-.idea
-src
-logic
-objects
-tests
-test
-test.java
src and tests are directories marked as Source and Test. Every package except test is empty. On my other PC with IntelliJ Community Edition everything works fine but on EAP there is this bug. Unfortunatelly I have to use EAP.
test.java code:
package test;
import org.junit.Test;
public class test {
#Test
public void canCreateInhabitant(){
}
}
Have you checked if you have the JUnit plugin enabled? I (foolishly, shame!) disabled it at some point and was unable to get IDEA to run my tests until I remembered to turn the plugin back on...
Check the root directory of your classes. It must be marked as source (for java classes) or test (for java test classes).
It seems that your directory is not well marked in IntelliJ.
I did a simple test and put it on github.
It's the absolute simplest of tests but it works great, standing inside the test class pressing shift+ctrl+t will run the test.
Go ahead and clone it and try it out.
Easiest way is:
Open Class in Intellij and press Ctrl+Shift+T
Select "Create New Test"
Now, a new pop up will be opened where you can select Unit Test Library (For your case its Junit4)
Select the methods which you want to include in test
And there you go !
Sometimes I find that this happens when I try and launch "All tests" from the project folder in the structure view. Launching all tests by right clicking on the test root folder and selecting "all tests" from there seems to solve it.
Just had this happen to me. When I built via Maven it had a problem. When I fixed the problem, it would run the junits again. Goofy.
I had the same problem, I solved it by clicking File-> Invalidate chaces and Invalidate an Restart

Run JUnit tests from a dependency jar in Eclipse

I have some JUnit tests that contained in a .jar that is intended to be used as a library. The library contains some tests that should be run whenever the library is used in another project.
However when I create a new project using the library and run JUnit on it in Eclipse then the tests in the dependency .jar don't run / don't get detected by the JUnit test runner. I get the message:
No tests found with test runner 'JUnit 4'.
Is there a way I can configure the dependency .jar so that the tests will run alongside any tests that might be contained in the main project?
Basically I want the dependency .jar to "export" the tests to whatever projects it is used in.
I'm using Eclipse Juno, JUnit 4.10, and Maven for the dependency management.
EDIT:
The point of this library is to be able to help test projects that use it - i.e. it runs some specialised tests. This is why I want to be able to import the library .jar and have it contribute the extra tests to the importing project.
You can try Maven Surefire.
In some cases it would be useful to have a set of tests that run with various dependency configurations. One way to accomplish this would be to have a single project that contains the unit tests and generates a test jar. Several test configuration projects could then consume the unit tests and run them with different dependency sets. The problem is that there is no easy way to run tests in a dependency jar. The Surefire plugin should have a configuration to allow me to run all or a set of unit tests contained in a dependency jar.
This can be done as follows (Junit 3):
Ensure test jar contains a class which has a static suite() method
import junit.framework.Test;
import junit.framework.TestSuite;
public class AllTests {
public static Test suite()
{
TestSuite suite = new TestSuite( "All Tests");
suite.addTestSuite(TestOne.class);
suite.addTestSuite(TestTwo.class);
return suite;
}
}
Then in the project using the test-jar dependency:
create a TestCase:
package org.melati.example.contacts;
import org.melati.poem.AllExportedTests;
import junit.framework.Test;
import junit.framework.TestCase;
public class PoemTest extends TestCase {
public static Test suite()
{
return AllExportedTests.suite();
}
}
Now the tests will be found.
I think that making a library of unit tests (#Test annotated methods) is a bad idea. However, making a library of reusable test components is a good one. We've done this in a few open source projects, and you can take a look how it works.
One Maven module exports test components (we call them "mocks"), from src/mock/java directory. Exported artifact has -mock classifier. See rexsl/pom.xml (pay attention to highlighted lines).
Mock artifacts are being deployed to Maven Central, together with usual artifacts: http://repo1.maven.org/maven2/com/rexsl/rexsl-core/0.3.8/ (pay attention to ...-mock.jar files)
Modules that need that mocks can include them as usual artifacts, for example rexsl-core/pom.xml (see highlighted lines):
Then, in your unit tests just use the classes from that mock libraries, like regular builders of mocks, for example: BulkHttpFeederTest
That's how you can make your test artifacts reusable, in an elegant way. Hope it helps.
#Mikera,
I find that this may help you. Just extend the Testcase Class to one of your java classes in project and you can run that particular class to run it as a JUnit Test.
I am not sure that this is desirable - On the one hand, if you use a jar, its behaviour might be influenced by the external context, e.g. other libraries in the classpath. From inside the jar, there is no simple way to analyse this context and to adjust the tests accordingly. On the other hand, if you write and compile a library, you should test it before packaging it as a jar. You might even want to not include your tests.
If it is really important to you to run the tests again, I would be interested in what could make them fail without changing the jar. In that case, however, you might want to extend the testrunner. As far as I know it uses reflection. You can quite easily load jars in a classloader and go through all their classes. By reflection you can identify the test classes and assemble testsuites. You could look into the testrunner for an example. Still, you would need to start this process from outside, e.g. from inside one of your test classes in the client project. Here, QATest's approach might be helpful: By providing an overriden version of testsuite or testrunner, you could automate this - if the client uses your overridden API.
Let me know if this rather costly approach seems to be applicable in your scenario and I can provide code examples.
Why should the user of the jar run the test cases inside the jar!!! When the jar is packaged and delivered, it means that the unit tests are run successfully.
Typically, the jar itself should be either treated as a separate project or as one of the modules. In both the cases, unit test cases are run before its delivered.

Can't run JUnit in Eclipse Indigo

I create simple Java Application project with src and test folders. src folder consists of the class which I test and test folder consists of the class where I describe test. When I start testing, using JUnit 4 I get: Could not find the main class: org.eclipse.jdt.internal.junit.runner.RemoteTestRunner. Program will exit. error. All JAR files are presented in my project.
What did I miss in my project?
That is a class that is part of the Eclipse plugin, it sounds like you have a corrupted installation of Eclipse. Try with a fresh installation.
Far shot: is the test-folder containing the .java-files for your tests also declared as a source-folder in the project's Build Path settings?
All JUnit tests should be written as follows:
#Test //This is very very important
public void testAbc()
{
//Test Abc() here....
}

How to use JUnit with Eclipse

I am a long time user of Eclipse but a novice when it comes to JUnit. I have lots of java projects and I want to start writing test cases around the methods in those projects. I'm just wondering the best way to set up the Eclipse environment for this purpose. Let's assume I have a typical project with a typical src directory in a specified package. How do I attach test cases to that project. Some concerns:
1. I don't want the test cases to be part of any build that I create on the project.
2. I want to refer to the clases in the test-suite.
Do I set up a separate test directory under the package I want to test? Do I have a separate test package? What is the best way to do this?
It's pretty dead simple:
Drag or otherwise place the JUnit jar file into your lib folder, then
modify your projects build settings to include it.
Create another source folder under your project called 'test'
Create your test packages underneath the 'test' source folder. Best
practice is to mimic the package names of your application.
Create your test classes inside of the test packages. Best practices
is to mimic your application classes that require testing, but append
Test at the end of the name. So for example in your main application
you might have a myapp.service.PrintService and as a corresponding
test you would have myapp.service.PrintServiceTest
Extend each test class from junit.framework.TestCase
Run your test classes using TestRunner.
When you build your application's deployment bundle just exclude the 'test' source folder. Now, if you want really drop dead easy test integration then use Maven to setup your project. It bakes in all the best practices for you right off the bat.
The best (or at least the most common) way to organize the test code it is to have a separate source folder for the test code, thus keeping it nicely separated. In eclipse, you can add source folders under "Build Path" in the project's properties.
However, it is also a good idea to keep your test classes in the same packages as the classes to be tested (i.e. have the same package hierarchy in the test source folder). This allows you test code to call package private and protected methods, making it much easier to test internal behaviour that should not be exposed in the public API.
A simple solution would be to create another source directory specifically for test-related classes. For example, if your main classes live in $PROJECT_ROOT/src, you can put your test-related classes in $PROJECT_ROOT/src-test. I don't have Eclipse handy, but I know that you can modify the $PROJECT_ROOT/.classpath file (it's XML) to include this new directory:
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="src" path="src-test"/> <!-- ADD THIS ONE -->
...
</classpath>
Now, all your test classes will see the main classes, but they won't be included in your build. I typically make sure that the test class lives in the same package as the class it's testing. That way, any protected members can be accessed from the test code.

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