Junit cases on property load fails on command line build - command-line

I have method in class with below code and I have written a junit for the same. This works fine when I right click -> run as -> junit in eclipse. But when run the application build in my command line "gradle clean build", it is failing the test case with the below error on the line of load.
java.lang.NullPointerException
at java.util.Properties$LineReader.readLine(Properties.java:434)
at java.util.Properties.load0(Properties.java:353)
at java.util.Properties.load(Properties.java:341)
Any thoughts on this?
inputStream = ClassLoader
.getSystemResourceAsStream("com/tgt/resources/file.properties");
fileProps = new Properties();
try {
props.load(inputStream);
} catch (IOException e) {
log.error("Property file missing");
}

Make sure file.properties is in src/test/resources. Eclipse will find files in all sorts of places, even if it's not the correct place that gradle requires.

Related

Could not find main method from given launch configuration

I've a simple Java project that works when I execute it at Eclipse environment. But when I try to export it to a Runnable Jar, I get the following error:
JAR export finished with warnings. See details for additional information.
Exported with compile warnings: JavaSwing/src.main.java/com/cansoft/GUIProgram.java
Exported with compile warnings: JavaSwing/src.main.java/com/util/Util.java
Jar export finished with problems. See details for additional information.
Could not find main method from given launch configuration.
I read other posts which suggest to create a MANIFEST.MF file specifying the main-class which I did. It is placed at MyProjectFolder/META-INF/MANIFEST.MF and it contains the following information:
Manifest-Version: 1.0
Class-Path: resources
main-class: com.cansoft.GUIProgram
My main class is as follows:
public class GUIProgram {
private JFrame folderCreationSubappFrame;
private Color color;
private String home;
private final static Logger LOG_MONITOR = Logger.getLogger("com.cansoft");
public static void main(String[] args) {
try {
new GUIProgram();
} catch (Exception e) {
LOG_MONITOR.log(Level.INFO,e.getMessage());
}
}
public GUIProgram() throws InterruptedException, SecurityException, IOException {
home = System.getProperty("user.home") + File.separator + "Documents";
startLogSystem();
if(isFirstRun()) {
showWelcomeFrame();
} else {
initialize();
}
} .... More and more code
Does anybody know what am I missing? Any help much appreciated.
Thank you.
It is not enough to create the manifest file, you need to explicitly choose it in the Eclipse jar export dialog.
Answer to Comment
If you use "runnable jar", make sure that you chose the correct launch configuration and that the launch configuration successfully runs when chosing "Run As" -> "Run Configurations" -> "Java Application" -> Your Configuration -> "Run"
I finally find out where the problem was, it was quite simple btw. I had created my GUIProgram within a src.main.java package, but that package was created (my bad) as resources instead of folders, so Eclipse was smart enought to run it but when trying to generate the JAR which expected a correct java project structure, it was failing because truly there were not GUIProgram java class at src path (src was not folder type but resources).
Hope I succeed explaining.

Eclipse keep saying "No tests found with test runner JUnit 5"

I am using Eclipse Oxygen.3 Release (4.7.3). The following is my JUnit test class:
import static org.junit.Assert.assertEquals;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
class MyMathTest {
MyMath myMath = new MyMath();
#Before
public void before() {
System.out.println("Before");
}
#After
public void after() {
System.out.println("After");
}
#Test
public void testSum_with3numbers() {
System.out.println("Test1");
int result = myMath.sum(new int[] {1,2,3});
int expected = 6;
assertEquals(expected, result);
}
#Test
public void testSum_with1numbers() {
System.out.println("Test2");
int result = myMath.sum(new int[] {3});
int expected = 3;
assertEquals(expected, result);
}
#BeforeClass
public static void beforeClass() {
System.out.println("Before class");
}
#AfterClass
public static void afterClass() {
System.out.println("After class");
}
}
When I run this Junit test, eclipse keeps popping up dialog telling "No tests found with test runner 'JUnit 5'". Why?
Your test class is currently based on JUnit 4 since it uses annotations from the org.junit package.
Thus, to get it to run as a JUnit 4 test class in Eclipse, you need to select the JUnit 4 Runner in the "Run Configuration". Click on the tiny arrow (pointing down) next to the green circle with a white arrow in it (at the top of the Eclipse IDE). There you should see your test class, and by selecting that you can switch between the JUnit 4 and JUnit 5 runners.
On the other hand, if your goal is to write a test using JUnit Jupiter (i.e., the programming model for JUnit 5), you'll need to switch from annotations in org.junit to org.junit.jupiter.api.
I had the same error, after trying everything, I have realized that the JUnit library wasn't added. So after adding it, tests worked as intended.
This happened to me because my test method was declared as private and JUnit could not detect it. After I made it public it worked as expected, of course with #Test annotation.
In Eclipse 2019-09 (4.13) is a bug that can cause the "No tests found with test runner 'JUnit 5'" error:
https://bugs.eclipse.org/bugs/show_bug.cgi?id=551298
I added the following dependency to my project and it worked for me:
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-commons</artifactId>
<version>1.5.2</version><!--$NO-MVN-MAN-VER$-->
<scope>test</scope>
</dependency>
the test class is not public, make it public and it should work
Take a look back to your imports.
You imports import org.junit.Test; (Used for run test cases with JUnit 4)
You need to import import org.junit.jupiter.api.Test; to run tast case with JUnit5.
You are using JUnit 4 annotations with JUnit 5 dependencies.
If you want to use JUnit 5 you should replace:
#Before with #BeforeEach
#After with #AfterEach
#BeforeClass with #BeforeAll
#AfterClass with #AfterAll
#Ignore with #Disabled
Here is more about JUnit 5 annotations https://junit.org/junit5/docs/current/user-guide/#writing-tests-annotations/
Right click the java file and choose:
Build Path -> Configure Build Path -> Java Build Path.
Choose the tab Libraries in Java Build Path, On the right side tab choose Add Library.
Select JUnit and click Next.
Choose JUnit 5 in JUnit Library version dropdown and click finish.
Now run the Test with Junit Test, it will work.
This procedure worked for me.
right click and run as -> config-> make this change and run it will works cheers!!.
My 2 cents:
Right click on project -> Configure -> Add module-info -> Give some random name.
It should automatically add there a requires in the JUnit package, if not, then manually add this:
requires org.junit.jupiter.api;
And it will magically work!
* tested on Eclipse 2018-12
My issue was that, Run works fine, debug throws this error.
I was getting this merely because of low memory in the system. Ideally, eclipse couldn't launch the debug session due to low memory in the system. Error message thrown is confusing.
Hope it helps someone!
In my current case, I encountered this error when testing the pact verification on the Service Provider side.The error was thrown because the Pact Broker doesn't have any pact to test against the Service Provider.
Visit the pact broker and ensure that there is at least one pact to test with.
I had the same problem with an Eclipse (2020-09) non-Maven project. None of the proposed solutions worked, but changing the compiler from 9.0.4 to 15.0.1 did.
I did that by selecting Preferences > Java > Installed JREsand checking the box next to jdk-15.01. You may need to install a recent JDK if none are shown.
Adding the JUnit vintage dependency fixed the issue for me.
https://junit.org/junit5/docs/current/user-guide/#migrating-from-junit4-running
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<scope>test</scope>
</dependency>

Why this exception not thrown under Junit in Eclipse?

all
I am scratching my head over a problem I ran into with junit test under Eclipse in particular:
Basically, I have a junit 4 test class, the initialization method annotated with
#BeforeClass tries to set up the DB connection, which essentially calls:
try {
return DriverManager.getConnection (DB_CONNECTION_URL,
DB_USERNAME,
DB_PASSWORD);
} catch (SQLException ex) {
throw new MyPersistenceException("Error: unable to connect to database");
}
Now, if I ran the code in a standalone main(), the exception is thrown as expected when database is offline. However, as soon as I move it into junit #BeforeClass, the exception seems lost in blackhole - you can still trace to the exception (remember, the database is offline), but nothing prints in the console.
I am baffled by the behavior, and seems have something to do with Eclipse and Junit in particular (the same unit test run fine under NetBean) - so it is a kind shot in the dark to see anyone experience any similar problem or got any idea ...
Thanks
Oliver
I think this might be a bug in the Eclipse plugin. I've traced the code in JUnit 4 source. The class RunBefores will throw an exception as you mention. However, the exception will go into the EachTestNotifier's failure list via the addFailure. If the plugin is ignoring something, it could explain why the issue is missed.

Scala project won't compile in Eclipse; "Could not find the main class."

I have installed Eclipse 3.5.2 and today's Scala plugin from /update-current (that's Scala 2.8 final.) I can compile and run Scala projects consisting of a single singleton object that implements main().
But, if a project contains more classes, I receive the "Could not find the main class" error.
I have tried searching for the solution and I discovered:
Eclipse is correctly looking for the Main$ class, not the Main class
* under Debug Configurations, my main class is correctly identified as mypackage.Main
* my plugin is up to date and recommended for my version of Eclipse
* cleaning, restarting etc. doesn't help.
The same project will compile with scalac.
Thanks for any ideas on how to solve this.
EDIT: MatthieuF suggested I should post the code.
This snippet produces an error. It's not the most idiomatic code, but I wrote it that way to test my environment. I tried it as a single file and as separate files. It DOES work with scalac.
import swing._
class HelloFrame extends Frame {
title = "First program"
contents = new Label("Hello, world!")
}
object Hello {
val frame = new HelloFrame
def main(args : Array[String]) : Unit = {
frame.visible = true
}
}
BUT, if I nest the definition of HelloFrame within Hello, it works. This snippet runs perfectly:
import swing._
object Hello {
class HelloFrame extends Frame {
title = "First program"
contents = new Label("Hello, world!")
}
val frame = new HelloFrame
def main(args : Array[String]) : Unit = {
frame.visible = true
}
}
For me, the problem was that there was a build error (see Problems tab) which was preventing compilation; oops! The reason you see the error is that the run macro proceeds despite the failed compilation step, and attempts to run class files it expects to be there; they don't exist because there was a build error preventing compilation, so it says it can't find Main (not compiled).
Problem goes away when build can complete successfully, i.e. errors are fixed.
I guess, theoretically, there may be more complicated reasons your build is not completing successfully that are not listed in Problems.
One possibility is that you are trying to launch using ctrl-F11, but from a different class.
The Scala Eclipse plugin does not obey the defaults for Java launching. In Preferences->Run/Debug->Launching, there are some options Launch Operation->Always Launch the previously selected application, etc. This currently does not work in the Scala eclipse plugin. To launch a specified main, you need to launch it from the editor for the class.
There has been a bug raised for this. http://scala-ide.assembla.com/spaces/scala-ide/tickets/1000023-scala-launch--does-not-follow-jdt-behaviour
EDIT: This is now (mostly) fixed.
For me it was Eclipse specific problem. I noticed that .class file wasn't built at all. So bin directory doesn't have compiled classes.
When I manually compiled *.scala file using *.sbt and copied it to bin directory it was working as expected.
I tried different tips and tricks and it wasn't worked until I reinstalled Scala plugin in Eclipse .
I'd solve similar problem by executig "Project->Clean.." with next automatically building.
I had the same error message with a Java application made by myself.
The problem was that I deleted (though inside Eclipse) a jar that belonged to the Java build path, without deleting it from the Java build path (project's Properties window). When I did it the class could compile and run again.
Make sure that the .class files exist, usually below the bin directory.
In particular, if you have errors in unrelated files in the same project then the compilation may fail, and no .class files will be produced.
There can be the case of projects, containing errors, added to the build path of the application which prevents the completion of successful compilation. Make sure you remove any such project from the build path before running the application.
Removing these projects solved the problem for me.
Do you have a proper build tool setup? Like sbt have you installed it?
You can check its version by $sbt --version
If it is not setup you can download from here http://www.scala-sbt.org/download.html
You might have to restart your eclipse after installation.
Just copy your XXX.scala file code. Remove the package and create a new Scala Class. Paste your XXX.scala code. (If you are using maven, do a maven clean and build.) Run configuration again. This works for me.
I have faced this issue. I have just deleted the package name, created scala class, Written the same code, Set Build to "Build Automatically". Finally, It works perfectly fine.
Check scala-ide.log
For me the issue was that there were errors on:
AppData\Local\Temp\sbt_10d322fb\xsbt\ClassName.scala:16: error: not found: value enteringPhase
enteringPhase(currentRun.flattenPhase.next) { s fullName separator }
If you are using Intellij, mark directory as source root

Debug some PhpUnit tests in Eclipse

I use Eclipse PDT for PHP.
I can run my PhpUnit tests : works fine.
But I can not debug my unit tests.
Has someby already done this ?
Can somebody help doing this ?
Thanx,
Messaoud
An example is more worth than 1000 words :
require_once 'PHPUnit/Framework.php';
require_once 'PHPUnit/TextUI/TestRunner.php';
class MyTestCase extends PHPUnit_Framework_TestCase {
protected function setUp() {
parent::setUp ();
}
function testSimple() {
echo "horray !";
}
protected function tearDown() {
parent::tearDown();
}
static function main() {
$suite = new PHPUnit_Framework_TestSuite( __CLASS__);
PHPUnit_TextUI_TestRunner::run( $suite);
}
}
if (!defined('PHPUnit_MAIN_METHOD')) {
MyTestCase::main();
}
the key thing is :
provide a main method in your testcase
test if the test is executed directly (via php MyTestCase.php) or by phpunit itself. if executed directly - just start the testrunner.
know you can debug your testcase.
We can solve this issue with our Eclipse plugin MakeGood.
MakeGood provides a simple way to debug your tests. You only run a test in Debug Mode.
For more information, see the user guide.
For others who are wondering if there are simple instructions for configuring Eclipse/Aptana with phpunit, here's a website I have found:
http://pkp.sfu.ca/wiki/index.php/Configure_Eclipse_for_PHPUnit
What you have to do basically is:
Make sure your PEAR libraries are in your project's include path. Right click on the project in the navigator window and click Properties. You'll see there's a section for PHP Include Path (or PHP Build Path in Aptana for my version), open that and add your PEAR libraries to your include/build path so that Eclipse knows about phpunit.
Create a debug configuration which runs the phpunit.php file (you might need to add the .php extension to the file if it is running with a shebang, as the case is in Mac OS X).
So with phpunit.php file as the "Start Action" script, set "PHP Script Arguments" so that the PHPUnit testing file you are interested with is run by phpunit.php. Add any other command line arguments, to suit you. eg. --verbose is a good option. You can also use variables like ${resource_loc} to have Eclipse replace it with the current file for example.
Run your debug configuration and enjoy debugging!
You do not need to modify your test files or anything, they'll work out of the box.
I finally run debugging parallel to command line in eclipse 3.4. Debugging i run as "PHP web page", my minimal code
require_once 'PHPUnit/Framework.php';
require_once 'PHPUnit/TextUI/TestRunner.php';
class XTest extends PHPUnit_Framework_TestCase{
public function testX(){
//...
}
}
if (!defined('PHPUnit_MAIN_METHOD')) {
header('Content-type:text/plain; charset=utf-8');
PHPUnit_TextUI_TestRunner::run( new PHPUnit_Framework_TestSuite( 'XTest'));
}
I have confirmed by setting a breakpoint in my setUp() method inside my unit test by following the instructions here:
How to Debug Your PHP Unit Tests in Eclipse
It involves copying the /usr/bin/phpunit file to your project (so it's accessible through eclipse's GUIs), and add the .php extension to it. From there, goto your debug configs and set the PHP-File to that phpunit.php file.
The next important step worked great for me, because I'm using Yii which provided me with a bootstrap.php file. Put something like this in your args:
--bootstrap=${workspace_loc}/my-project/trunk/protected/tests/bootstrap.php ${workspace_loc}/my-project/trunk/protected/tests/unit/SomeClassToTest.php