Java (maven) : how to know where lies the error (useless backtrace) - java

I'm writing my first project with maven (here). When I run the tests with mvn -Dtest=EchoTest test, I get a BUILD FAILURE with
nonAcceptedTypeVerification(EchoTest) Time elapsed: 0.044 sec <<< ERROR!
java.lang.NullPointerException
at EchoTest.initialize(EchoTest.java:50)
How can I know more precisely what line in my code triggers the NullPointerExcepion ?
In other words : how to ask Maven to print the whole backtrace ?
I tried mvn -e, and searched in the target subdirectory.
EDIT
Here are the lines provoking the NullPointerException (in EchoText.java) :
#Before
public void initialize() throws InterruptedException
{
system = new EchoActorSystem();
echo_actor = system.actorOf(); <-- line 50
}
The point is that EchoActorSystem is a quite complex class and the method actorOf makes tons of work, calling many functions from system. For example it calls super.actorOf() and then fix some properties of the result, and so on.
I'm searching the faulty line by adding many Sysytem.out.println, but I'm sure that this is not the right way to work.

mvn test -Dtest=EchoTest -DtrimStackTrace=false will give you the complete stack trace.
The magic is -DtrimStackTrace=false.
Maven will default to chopping the stacktrace down to just the lines that appear in your test. Honestly this is the first time I've ever noticed this behaviour and it feels to me a very odd default (I can understand for the console output, but in the surfire-reports XML reports as well?)

You'll find the complete stacktrace it in the target/surfire-reports directory, file EchoTest.txt

Related

Mockito with JUnit Failing on Windows

I have just received a new project, I have a fresh repo clone of a java spring project.
When I build it with Gradle, all the dependencies are downloaded but when one of the Gradle tasks execute, the unit tests, the build fails.
I think the problem resides in the argThat() method of Mockito that is not getting well integrated with JUnit. This is one of the places where the issue occurs:
Any time a unit tests have this kind of logic, it fails with:
The console output is not for the above test but it is a similar method with more complex logic.
The above tests still fail with the same issue.
This only happens in my machine and not on others that are on a Unix distribution, fedora.
I think the problem is due to the dependencies version, but I have tested with different ones to no avail.
I can give you more information if needed.
Thank you.
EDIT: Code - not a screenshot
#Test
void shouldAbortEventExecutionWhenJobFails() throws JobParametersInvalidException, JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException {
when(jobLauncher.run(eq(job1), argThat(jobParametersForPath(TEST_PATH_1)))).thenReturn(jobExecutionFailed);
when(job1.getName()).thenReturn("job1");
ExecutionState result = executor.execute(asList(event1, event2));
assertThat(result).isEqualTo(ExecutionState.FAILED);
verify(jobLauncher).run(eq(job1), argThat(jobParametersForPath(TEST_PATH_1)));
verify(jobLauncher, never()).run(eq(job2), argThat(jobParametersForPath(TEST_PATH_1)));
verify(jobLauncher).run(eq(job1), argThat(jobParametersForPath(TEST_PATH_2)));
verify(jobLauncher).run(eq(job2), argThat(jobParametersForPath(TEST_PATH_2)));
verifyNoMoreInteractions(jobLauncher);
}
private ArgumentMatcher<JobParameters> jobParametersForPath(String inputPath) {
return jobParameters ->
jobParameters.getParameters().get("inputFilePath").toString().equals(inputPath) &&
jobParameters.getParameters().get("outputFilePath").toString().equals(TEST_OUTPUT_PATH + "/" + inputPath) &&
jobParameters.getParameters().containsKey("timestamp");
}
I can't tell you the exact problem without inspecting your code or without reproducing your issue. But I guess the problem should be related to file paths;
I can see that there is a variable called outputFilePath inside your assertation object. in Linux environments, we use slash / for file paths, but in windows environments it's back-slashes \.
[1] https://www.howtogeek.com/181774/why-windows-uses-backslashes-and-everything-else-uses-forward-slashes/
[2] https://stackoverflow.com/a/1589959/3728639
You need to debug your Junit test and compare actual assertation object with the expected one

Generating Failure in junit4

I am trying to understand which call causes Error and Which causes failures in Junit4. Until Junit3,
Failure can be created using
junit.framework.AssertionFailedError
And Error with
junit.framework.Assert.assertEquals
But with the deprecation of junit.framework.Assert, which is not moved to org.junit.Assert, I am not able to find a way in junit4 to throw a failure. Anything I try with org.junit.Assert (even Assert.fail() ) , JUnit considers it as Error.
Any idea on how to properly generate failures in Junit4 style tests?
Update
I figured out that there is a std.err at the end of XML generated by JUnit ant target.
<system-err>TEXT here</system-err>
and I suspected this is the cause that making it ERROR instead of Failure. But when I cleared all sys.err, it still marking it ERROR.
You can still use Assert.assertThat for getting assertion failure
assertThat(0, is(1)); // fails:
assertThat(0, is(not(1))) // passes
It may not what you need, but also JUnit 4 has ComparisonFailure
Thrown when an assertEquals(String, String) fails. Create and throw a ComparisonFailure manually if you want to show users the difference between two complex strings.
I am having the same issue. The only solution I have found so far is to use a try block followed by
catch (AssertionError ae) {
fail(ae.toString());
}
But I can see downsides to this and I have seen many people say this is bad practice. Unfortunately I don't see another way around it when using ant to make a report.

Debugging ActiveJDBC with IntelliJ IDEA

I am new to ActiveJDBC. I am trying to debug the sample project.
The code I want to debug is:
public static void main(String[] args) {
Base.open();
Person director = new Person("Stephen Spielberg");
director.saveIt();
//[break point here]
director.add(new Movie("Saving private Ryan", 1998));
director.add(new Movie("Jaws", 1982));
director.getAll(Movie.class).forEach(System.out::println);
Base.close();
}
The code compiles correctly and the instrumentation is properly executed (I believe) (have a look here).
The debugger is launched and paused at the defined break-point.
I am trying to evaluate the expression "Person.count()" and I am expecting the result to be 1.
But I have the following error in the 'Evaluate expression' window:
Method threw 'org.javalite.activejdbc.InitException' exception.
failed to determine Model class name, are you sure models have been instrumented?
Have a look: https://unsee.cc/nipareto/
It is possible that you recompiled models after instrumentation unintentionally. If you instrument, then make any change to a model, and then try to run your code, and IDE will detect the change and recompile your model, thus blowing away instrumentation.
Ensure you instrument before you run your code.
Additionally, the link you provided: https://github.com/javalite/activeweb-simple is not corresponding to code. I think you are using this one: https://github.com/javalite/simple-example. If so, try running on command line according to README.
Debugging models in ActiveJDBC in IDEA is what I do daily:)
Also, I recommend you watch the video on this page: http://javalite.io/instrumentation because it walk you step by step using IDEA.
UPDATE April 10 2017:
I recorded this video to show you how to instrument and debug an ActiveJDBC project: https://www.youtube.com/watch?v=2OeufCH-S4M

How to know from which line within a function an exception is occuring in Java?

When developing an application, we normally use different functions from different classes. Now a function can be written in a way, where only the different functions are called. So
I just want to know suppose I am having a function where I have called some other functions and also having unique code in that function. So how I will know for a bigger project, that from which line for a particular function, exception is occurring in Java.
At most, right now I can detect only from which function exception is occurring. But I need specific portion(specific line) of that function where the exception is occurring.
Any helpful answer will be appreciated.......Thanks in advance......!!!!!
catch(Exception e){
e.printStackTrace();
}
this would do the trick.
The rest of answers written here are perfectly relevant and true, but there is a little gap. You must remember to include in your binary files the relevant debug information, or if not, the JVM will not know which line number caused the exception. Remember to set the debug flag when compiling your code, have a look at this from the javac help:
C:\>\j2sdk1.5.0\bin\javac
Usage: javac <options> <source files>
where possible options include:
-g Generate all debugging info
-g:none Generate no debugging info
-g:{lines,vars,source} Generate only some debugging info
You would need to compile with javac -g xxx.java, or at least javac -g:lines xxx.java in order to have that information on execution time. If you compile your code by any other means (Eclipse or any other IDE compiler, ant, maven, gradle...) you should have a look at your automation tool compiler doc in order to know how to instruct its compiler to generate debug information along with your binaries.
You look at the stacktrace. For example:
java.io.FileNotFoundException: test.txt
at java.io.FileInputStream.<init>(FileInputStream.java)
at FooBar.test(FooBar.java:19)
at FooBar.main(FooBar.java:7)
To get the execution order you have to read it from bottom to top.
Here
the program starts at the method main() of class FooBar
main() calls the method FooBar.test() in line 7 of FooBar.java
test() calls the FileInputStream constructor in line 19 of FooBar.java
the FileInputStream constructor throws an FileNotFoundException
You can print the stacktrace of an exception using:
try {
..
} catch (Exception e) {
e.printStackTrace();
}
try
{
//your code that may have error
}
catch(Exception ex){
ex.printStackTrace();
}
suppose there's error occur then it will show something like this :
Exception in thread "main" java.lang.NullPointerException
at com.example.myproject.Book.getTitle(Book.java:16)
it means error at line number 16 in Book.java.
look this article

Another Netbeans issue | cannot find symbol method, but correctly declared

this has been a crappy day, besides the IDE not compiling/deploying because of this bug and waisting valuable time, I finally get it to deploy it suddenly I start getting this weird message (after compiling and running it several times):
T:\Users\Triztian\Documents\RHT System\RHTUBSDB\src\java\controllers\OrderSearch.java:64: cannot find symbol
symbol : method metadata(java.lang.Long)
location: class BO.CoverForm
OrderExtraInfoDTO foundInformation = frmCover.metadata(foundOrder.getReferenceNumber());
it is my understanding that this means that my method isn't declared, but thats not the situation as my method is clearly declared and coded.
CoverForm.java:
public OrderExtraInfoDTO metadata(Long ReferenceNumber) {
OrderExtraInfoDTO foundInformation = new OrderExtraInfoDTO();
try{
foundInformation = lnkAddInformation.fetchInformation(ReferenceNumber);
} catch (DAOException daoe) {
this.setError("additional_information", daoe.getMessage());
}
return foundInformation;
}
And the servlet that calls the CoverForm.java method.
OrderSearch.java (Extends HttpServlet):
CoverDTO foundCover = frmCover.search(foundOrder.getReferenceNumber());
OrderExtraInfoDTO foundInformation = frmCover.metadata(foundOrder.getReferenceNumber());
UpgradesDTO foundUpgrades = frmUpgrades.search(foundOrder.getReferenceNumber());
I've tried renaming the method and didn't have any success, any help is truly appreciated as I'm getting frustrated with NB 6.9.1 because of some crashes and another weird bug (might catch an entomologist's attention) which locks the editor and displays a message saying: "Refactoring cannot be done in the given context" whenever I press delete, forcing me to restart the IDE.
EDIT
Ok, so I've removed the classes that I posted and merged them in a more appropriate place, however I still get that silly symbol not found error but on a different symbol(another method) this time.
Netbeans 6.9.1 is a very robust IDE. You may run into problems like the one you mention above, if:
You run your NB without enough disk space available. Make sure that you have at least 2 GB free on your file system for the necessary temporary files.
You have a very large number of projects active in your project space. Reduce this number to just the needed projects, by deleting and reopening more often.
Hope this helps ...

Categories

Resources