'No JUnit tests found' in Eclipse - java

So I'm new to JUnit, and we have to use it for a homework assignment. Our professor gave us a project that has one test class, BallTest.java. When I right click > Run as > JUnit Test, I get a popup error that says 'No JUnit tests found'. I know the question has been answered here(No tests found with test runner 'JUnit 4'), but closing eclipse, restarting, cleaning, and building doesn't seem to work. Below are screenshots of my run configuration, build path, and the class I'm trying to test.
BallTest.java
import static org.junit.Assert.*;
import junit.framework.Assert;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
public class BallTest {
Ball ball;
/**
* #throws java.lang.Exception
*/
#Before
public void setUp() throws Exception {
System.out.println("Setting up ...");
Point2D p = new Point2D(0,0);
ball = new Ball(p);
}
/**
* #throws java.lang.Exception
*/
#After
public void tearDown() throws Exception {
System.out.println("Tearing down ...");
ball = null;
}
/**
* Test method for {#link Ball#getCoordinates()}.
*/
#Test
public void testGetCoordinates() {
assertNotNull(ball); // don't need Assert. because of the import statement above.
Assert.assertEquals(ball.getCoordinates().getX(), 0);
Assert.assertEquals(ball.getCoordinates().getY(), 0);
}
/**
* Test method for {#link Ball#setCoordinates(Point2D)}.
*/
#Test
public void testSetCoordinates() {
Assert.assertNotNull(ball);
Point2D p = new Point2D(99,99);
ball.setCoordinates(p);
Assert.assertEquals(ball.getCoordinates().getX(), 99);
Assert.assertEquals(ball.getCoordinates().getY(), 99);
}
/**
* Test method for {#link Ball#Ball(Point2D)}.
*/
#Test
public void testBall() {
Point2D p = new Point2D(49,30);
ball = new Ball(p);
Assert.assertNotNull(ball);
Assert.assertEquals(ball.getCoordinates().getX(), 49);
Assert.assertEquals(ball.getCoordinates().getY(), 30);
//fail("Not yet implemented");
}
public static void main (String[] args) {
Result result = JUnitCore.runClasses(BallTest.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
}

Right Click on Project > Properties > Java Build Path > Add the Test folder as source folder.
All source folders including Test Classes need to be in Eclipse Java Build Path. So that the sources such as main and test classes can be compiled into the build directory (Eclipse default folder is bin).

If none of the other answers work for you, here's what worked for me.
Restart eclipse
I had source folder configured correctly, and unit tests correctly annotated but was still getting "No JUnit tests found", for one project. After a restart it worked. I was using STS 3.6.2 based of eclipse Luna 4.4.1

right click -> build path -> remove from build path
and then again add it ->
Right click on the folder named 'Test' > Build Path > Use as Source Folder.

I had the same problem and solved like this:
I deleted #Test annotation and retyped it.
It just worked, I have no idea why.

It looks like you're missing the runner definition on your test class, that could be the cause:
import org.junit.runners.JUnit4;
#RunWith(JUnit4.class)
public class BallTest {
...
}

Right click your project ->Properties->Java Build Path and go to Source Tab then add your test src folder.
Select Project menu and unselect 'Build Automatically' option if selected
Select Clean and then select 'Build Automatically' option
Restart Eclipse and run your junit.

junit4 require that test classname should be use Test as suffix.

Any solution didn't work for me until I change the name of the my test method. When name of test method starts with "test" is OK.
I am new in android programing and it was for me big surprise.

I think you have created your test classes outside the src folder. You can solve above problem by two way:
Add your package name in java build path->source
Move your package/class in src folder
I have the same problem and solved in this way both solutions working fine.

Try this
Right Click on the Unit Test Class,
Select "Run As" -> Run Configuration
In the "Test" tab, make sure in the field "Test runner" select drop down "JUnit 4"
Click "Apply"
Now Run the test!

I solved the problem by configuring the build path.
Right click on the project(or any of the subfolders)-> Build path -> Configure build path. Once the property window opens up, click on the 'Source' tab and add your src and tst folders.
But this alone did not work for me.
Strangely, I had to retype the annotations.(Project->clean or restart might also have worked though).

Came across this problem while upgrading projects across eclipse versions. For e.g. junits running well in Mars2.0 did not run on Neon. The following worked for me.
Delete .settings folder. Import project into eclipse.
Remove source folders. Then again use the folders as source folders. e.g - remove src/main/java from build path as source folder. -> Ok -> Again make this folder as source folder. Repeat it for main/resources, test/java, test/resources

In Eclipse Photon you may need to add JUnit 4 or 5 to the build path. Right click #Test and select 'Add JUnit 4 to build path'.

Click 'Run'->choose your JUnit->in 'Test Runner' select the JUnit version you want to run with.

The run configuration for a test class can create another cause (and solution) for this problem.
If you go to Run (or Debug) Configurations (using cmd-3 or clicking on the small dropdown buttons in the toolbar) you can see a configuration created for every test class you've worked with. I found that one of my classes that wouldn't launch had a run configuration where the Test Method field had somehow gotten inadvertently populated. I had to clear that to get it to work. When cleared it shows (all methods) in light text.
I'll add that strangely — maybe there was something else going on — it also seemed not to work for me until I fixed the "Name" field as well so that it included only the class name like the other JUnit run configurations.

I was using #RunWith(Parameterized.class) but missed to add the #Parameters annotation in the public static parameters method. After adding the annotation it worked.

The best way to resolve this issue is to put public Access modifier for your Junit Test Case class name and then run the scenario by right click on your Junit test case class and run as Junit Test.

The solution was, after making a backup of the src/test folder, removing it from the filesystem, then creating it again.
That's after I did the "Remove from build path" hint and it screwed the folders when opening the project in STS 4.

I had this problem too with JUnit 5.4.2. I use Eclipse 2019-09 with gradle 5.3.1.
So I had to add this two dependencies to build.gradle file with right configuration for it (testImplementation and testRuntimeOnly):
apply plugin: "java"
//enabled the Gradle’s native JUnit 5 support
test {
useJUnitPlatform()
}
testImplementation group: "org.junit.jupiter", name: "junit-jupiter-api", version: "${junitVer}"
testRuntimeOnly group: 'org.junit.jupiter', name: 'junit-jupiter-engine', version: "${junitVer}"

Some time if lots if Test files are there then Eclipse failed to pass -classpath options for all libs and path due to classpath param lenght limitations.
To Solve it go to Run
Configerations -> JUnit -> Your Project Config -> ClassPath -> Check "Use Temporary Jar Options"
At least it solved my problem.

Right Click on Project > Properties > Java Build Path > Libraries >
select classpath -> add Library -> Junit -> select junit version -> finish -> applay

Sometimes, it occurs when you add Junit Library in Module path. So, Delete it there and add in Class path.

Imported project in a new eclipse workspace, this resolved my issue.

Related

Problem getting "Programming in Scala" junit example to work in IntelliJ

Still learning Scala and Intellij with Scala plugin... Trying to get the SetTest class from the "Programming in Scala" 3rd edition book to work. Here is the code that I entered into IntelliJ Idea Community 2019.3 with the latest Scala plugin:
import org.junit.Test
import org.junit.Assert.assertEquals
class SetTest {
#Test
def testMultiAdd = {
val set = Set() + 1 +2 + 3 + 1 + 2 + 3
assertEquals(3, set.size)
}
}
I added the junit-4.3.1.jar to my project structure library via the Maven download option. Then I click on the double green arrow in the left margin of the editor and select "Run SetTest".
Then I get the error "Error:(4, 7) SetTest is already defined as class SetTest
class SetTest {"
So then I delete the SetTest run configuration that IntelliJ generated. Then I click on the single green arrow in the left marging of the editor and select "Run TestMultiAdd()". This causes the exact same error.
I've also tried to set up different run configurations manually with no success. Help please!
Try use sbt dependency instead of manual add library.
Add it to build.sbt:
libraryDependencies += "junit" % "junit" % "4.12" % Test.
If Intellij Idea will suggest you import changes for SBT project, then do it. Else Idea make it automatically. Also you can import it manually via command line: sbt reload and sbt clean package.
Check than file name is equal to class name (commonly it's not required for Scala)
Try run test again.
It's work for me.
You can find this or another dependency at mvnrepository.com. By default it show how to add maven dependency. But in section SBT
you will see line from 1st item.
Sorry for my English
Test should be named SetTestTest maybe then. There is already class named SetTest.

Maven and Intellij builds differently

I have a parent pom.
When I am on the parent and write mvn clean install my dropwizard application builds fine.
However, in Intellij it fails because it cannot find my config.yml file.
The problem is that I need to include my module directory in Intellij, but not in Maven. Why is that?
Running mvn install this works
public static void main(String[] args) throws Exception {
new CivilizationApplication().run(new String[]{"server", "src/main/resources/config.yml"});
}
In Intellij I must change to the following
public static void main(String[] args) throws Exception {
new CivilizationApplication().run(new String[]{"server", "civilization-rest/src/main/resources/config.yml"});
}
How can I configure Intellij, so it will work without specifying the module directory?
You could try setting your working directory in your run configuration...
I would also look into your pom.xml configuration to see if you can change the working source sets to use this directory upon importing the maven project.
Set Working directory to $MODULE_DIR$. Maven always uses $MODULE_DIR$, but you probably do not have $MODULE_DIR$ by default for IntelliJ Application executions.
You can just tell Intellij to do exactly the same thing Maven does when you start it.
You can do so by clicking on the drop down menu next to the "Launch App" button. There you can define a new Run configuration that uses Maven by clicking on the + to the left and then choosing Maven.
Then you can just enter clean install exec:java where it says "Command line" and it should work exactly like it does when you execute it manually from the command line. Debugging should work like this as well without any problem.
The problem here is that you are refering to a resource file by using a relative path instead of using the classpath.
So, instead of
new CivilizationApplication().run(new String[]{"server", "src/main/resources/config.yml"});
You better have this
new CivilizationApplication().run("server", getClass().getResourceAsStream("config.yml"));
(obviously, make sure to change the signature of the #run() method as well)
Just a thought but maybe it's to do with the Resource not being copied.
I'm on OSX so the exact terms may differ if you're on Windows but for me... in Preferences, select "Build, Execution, Deployment", then "Compiler", and try adding ";?*.yml" to the Resource patterns.

Testing Java code with Groovy under Intellij: unable to resolve class GroovyTestCase

I need to write a short test for some Java code. I used CTRL+SHIFT+T to generate one with IntelliJ, and selected "Groovy JUnit" as the testing library, then wrote the following test:
package util
class FibonacciHeapTest extends GroovyTestCase {
FibonacciHeap<Integer> heap
void setUp() {
super.setUp()
heap = new FibonacciHeap<>()
}
void testAddInOrder() {
testForItems 1..1000
}
private void testForItems(Range<Integer> items) {
items.each {heap << it}
assertEquals heap.size, items.to
items.each {assertEquals heap.remove(), it}
}
}
However, when I right click on the test case in the project window, I don't get the "Run All Tests" option that I normally do with JUnit tests, and the compiler throws the following error:
Information:2/4/15 8:15 PM - Compilation completed with 2 errors and 0 warnings in 2 sec
/home/patrick/IdeaProjects/hackerrank/src/test/java/util/FibonacciHeapTest.groovy
Error:(3, 1) Groovyc: unable to resolve class util.FibonacciHeap
Error:(9, 1) Groovyc: unable to resolve class GroovyTestCase
Trying to import GroovyTestCase or FibonacciHeap manually causes the same error. IntelliJ does not add any import statements when I let autocomplete finish the names for me, like it usually would with Java code.
What am I doing wrong?
This worked for me :
Open Gradle window (on right side in my case)
Click on refresh button
Done
I had a similar problem with creating test classes in IntelliJ, and it was solved when creating a new directory outside of the com.company folder (where I had the class I wanted to test).
Create a new directory for the test classes on the same level as your src folder
Right click on your new test directory, and "Mark directory as" --> "Test Resources Root"
Now create a test class, which should automatically be added to your test directory.
Build -> Rebuild project in the IDE itself (as opposed to maven, in my case) did it for me.
In my case, what I did to resolve the issue was rather simple.
Close IntelliJ
Open the attached homepage...
Remove your project by clicking on the x then...
Click on Import Project, Navigate to the build.graddle file of your project and open.
That was it and all the Red highlightings disappeared.
maybe you need add groovy-all rather then groovy,such as :
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>${groovy.version}</version>
</dependency>
You have to configure Groovy SDK first. See the screenshot
More detailed description in the official document: Configuring Global, Project and Module SDKs
As #sman591 pointed out in a comment, if you are getting the error:
groovyc: unable to resolve class groovy.util.GroovyTestCase
and you already have groovy as a dependency then you are probably just missing the junit dependency.
In IntelliJ IDEA I re-imported the project. It worked then.
I closed idea. I removed .idea folder in the project. And I imported the project.
Then I needed to set up Groovy, see previous answers, mark test directory as test source in all modules of my project.
I was selecting the root folder which had build.gradle file in it, but it didn't work.
Steps followed are similar to #Pila
close the project from intellij
remove .idea, log, out folders
go to intellij dashboard
import project from existing resources
select build.gradle file <-- this is important
now you should see all the tasks are getting build in the background, and once build is finished all red lines are gone.

Run As JUnit not appearing in Eclipse - using JUnit4

I'm trying to write JUnit4 tests for my web app, and they had been working fine previously. However, now when I try to run the tests by right clicking the class file -> Run As -> JUnit Test I don't see that option. I think it could be because a colleague committed some Eclipse settings/property files on accident that messed with mine. I'm using Eclipse Helios on a Mac running 10.6.X.
I noticed that the icons on the test classes changed from the "filled" J to a "bubble" J and I'm not sure if that is signifying some kind of problem:
I've double checked and made sure that JUnit4 is on my Build Path, and I've gone to the Eclipse -> Preferences -> JUnit pane and verified there are JUnit4 imports being used.
My test classes look like this:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration( { "classpath*:/resources/action-test-appconfig.xml" })
#Transactional
public class UserControllerTest extends BaseStrutsTestCase<UserController> {
/**
* Tests the ability of a user to change their login username
* #throws Exception
*/
#Test
public void testChangeLogin() throws Exception {
Any thoughts and suggestions are appreciated.
The problem is with the way you are trying to access and run java files in eclipse. You should be observing this empty 'J' icons on your java files. It is a classpath problem, when you click, you are actually accessing the file from the classpath.
To view the Java file, you have to add a reference to your project in the classpath and move it to the top of the classpath list.
Once you do that, then you should be able to run your junits.
I had the same issue, and I restarted eclipse and got "Run as JUnit test" back.
Looks like a bug in eclipse.
That kind of J icon filled to a "bubble" means that Eclipse doesn't recognize your project as a Java project, and therefore doesn't provide Java options such as Run as JUnit.
Try reimporting the project as a Java Project.
Try adding following dependency in the pom.xml of your project in which the test case is located:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>org.springframework.test</artifactId>
<version>3.1.1.RELEASE</version>
<scope>test</scope>
</dependency>

JUnit4 + Eclipse "An internal error occurred during Launching"

I'm trying to run JUnit4 test cases on Eclipse 3.4.2 but it's not even starting for me. I have the junit-4.7.jar in my build path and the test application.
Here is a simple example that illustrates my problem
package test;
import org.junit.Before;
import org.junit.Test;
public class UTest {
#Test
public void test() {
}
#Before
public void setUp() throws Exception {
}
}
This compiles fine
Then I do "Run JUnit Test case" from Eclipse and I get an error dialog with this message
"Launching UTest' has encountered a problem
An internal error occurred during: "Launching UTest".
java.lang.NullPointerException
What causes these NullPointerExceptions? What am I doing wrong?
What worked for me after trying everything:
Go to help
Install New Software
Work with: Juno
Programming languages (expand it)
Install Java Development Tools
Restart
It works :)
I was able to fix this just by deleting the workspace and the Eclipse directory and starting over.
This worked for me:
create another copy of the test class (CopyOfUTest.java)
run the copy to make sure it passes
go into Run > Run Configurations
under JUnit, find the run configurations for the original class and the copied class
right click and delete the configuration of the original class
rename the configuration of the copied class to the original configuration name
delete the copied class from the project
None of the given answers here worked for me, so I ended up just installing and using InfiniTest instead. It doesn't have this problem, and it also runs the tests automatically so I can focus on my work.
Have you looked in the Eclipse error log? You can see it by opening the "Error Log" view.
http://help.eclipse.org/help32/topic/org.eclipse.pde.doc.user/guide/tools/views/error_log.htm
This error In eclipse can be caused if you are also using the Android Development Kit plugins:
"Launching UTest' has encountered a problem
An internal error occurred during: "Launching UTest".
java.lang.NullPointerException
Can be caused if you are loading a normal Java project into an Eclipse instance with android ADT plugins installed and enabled. In this situation, Eclipse looks for "Android" project files, and doesn't find any. So it says: "NullPointerException".
So to fix it, re-download Eclipse without the ADT Plugin: https://www.eclipse.org/downloads/
Then re-import your project fresh. And the junit tests run without a problem.
Many people hate eclipse for it's enigmatic error messages. It's like we are back in the 1950's punch card world, where there are no error messages. The program just halts and undefined behavior occurs.
Thanks that solved my problem too.
The problem started when i removed an old simulator, and created a new one.
Fix: Like the OP says remove the workspace, make sure to keep the projects inside it :)
then import them back to eclipse
"Sound like a lot of work" ?
Took me less than half a minute !!!
If you are using Android and its associated plugins, then Android only supports JUnit 3.
I resolved the problem by selecting Test Runner as JUnit 3.
In my class, JUnit 4 is added in the build path->libraries.
Then to run the test file, go to: Run As -> Run Configurations then select the corresponding test.java file and select Test Runner accordingly(whether it is JUnit 3 or 4).
Your code works fine for me.
Eclipse
Version: 3.4.1
Build id: M20080911-1700
I right click on the .java file RunAs JUnit Test. This would indicate the problem is caused by an Eclipse configuration problem, not a code problem.
I encountered a similar problem but I am using Python. This is what I did to solve/avoid it:
Removed my .project file and the project from Eclipse.
Created the project again.
Everything was working.
The problem seemed to be in the .project file where there were some references to CDT Builder and were not there in the new .project file.

Categories

Resources