Why/how does JUnit pass tests with compiler errors? - java

I've just started learning about TDD and am trying to write a simple project that way.
I'm using Eclipse and JUnit, and every time I make a change I run all the tests in the relevant package.
But then I'm very surprised to see in the package explorer that one of my test cases has a big red cross indicating a compiler problem... Annoyed I figured that I got my eclipse shortcuts mixed up and haven't been running all the tests, as they are all passing.
But when I start fiddling about, I realise that it seems Eclipse + JUnit will run and pass tests even if there are compiler errors...
The JUnit test case:
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
public class ATestCase {
private Command command;
private Invoker invoker;
#Before
public void setUp() throws Exception {
command = new Command() {
public void methodA(){};
//haven't implemented methodB()
};
invoker = new Invoker(command);
}
#Test
public void test(){
invoker.invoke();
}
}
interface Command{
void methodA();
void methodB();
}
The Invoker class:
class Invoker{
private Command command;
public Invoker(Command command) {
this.command = command;
//if I invoke methodB() I get UnresolvedCompilationError
}
public void invoke(){
command.methodA();
//only if I call methodB here
//do I get Unresolved compilation problem
// command.methodB();
}
}
The command object I create in setUp in the test case only implements one of the interface's methods. This of course causes a compilation error warning in Eclipse.
However unless I actually call that method in the test case, the test passes.
If I do call the method, then the test fails with 'unresolved compilation error'.
Can anyone explain to me what exactly is going on?
******EDIT******
I'm not sure why this was closed as a duplicate.
Apparently I'm supposed to edit this question to make the difference clear:
Well the question I'm supposed to be duplicating asks in the first line:
What are the possible causes of a "java.lang.Error: Unresolved
compilation problem"?
The title of my question states I'm asking:
Why/how does JUnit pass tests with compiler errors?
As in how can code which shouldn't compile be run by JUnit without causing errors?
I fully understand the causes of the Unresolved Compilation Error, it's the obvious unresolved compilation error in my code. What I don't understand is how the error doesn't always occur (it only occurs when I specifically call an unimplemented method) and how the tests pass?!
It may be that these issues are related, but unless there is a specific answer explaining how they are related I fail to see how they are in any way duplicate questions...

When a class fails to implement an interface method, the Java compiler does not reject the code but instead emits bytecode for the method that will raise the runtime error seen. This explains why JUnit is able to run the tests and why the test passes if you don't call methodB - the runtime error does not get raised.
Per this page, this does not occur by default but requires that you have the Java -> Debug 'Suspend execution on compilation errors' setting enabled.

I'm assuming that is by design: to allow for testing specific methods without having to worry about whether other dependencies which the compiler would pick up on anyway are resolved or not. i.e. we shouldn't be using JUnit to tell us whether our entire project can compile or not.

Related

Can I force Intellij-IDEA to run an ignored test?

I wrote a performance test class marked as #Ignore because it takes a very long time to run and I don't normally need to run it. I'd like to be able to right click one of the #Tests and say "run" but when I do that in intellij it doesn't run the test because the class is marked as ignored.
I don't want to comment out the #Ignore because it's too easy to accidentally commit the file with the #Ignore removed. But I feel that if I explicitly tell Intellij to run a test it should run it regardless of the #Ignore. Keep in mind, if I run a group of classes (eg: all in a package) I still would want this test class to be ignored.
Is it possible to get this functionality in Intellij?
I found this link which says that you can do something tricky with Assume.assumeTrue that will mark the test as ignored if the condition is false, and normally this is a system property that is used in the condition, so you can pass it in as a parameter on the command line. IntelliJ lets you customize the command line parameters, so it should work, but I haven't tried it myself.
The example from the link is:
#Test
public void shouldTryEveryPossiblePhoneticAttributeSet() throws IOException {
Assume.assumeTrue(TestEnvironment.hasBigParseSets());
...
}
public class TestEnvironment {
private static final String HAS_BIG_PARSESETS = "hasBigParseSets";
public static boolean hasBigParseSets(){
return "true".equalsIgnoreCase(System.getProperty(HAS_BIG_PARSESETS));
}
}
And "mvn test -P bigParseSets" vs "mvn test".
edit: And I just found this neat thread on StackOverflow that tells how to run a single junit test. I assume I don't need to quote that since it's to a post here on StackOverflow. That explains how to do it from a command line, but you should be able to do something very similar to that one that has hard coded values for the class and method names, and then just right click on the SingleJUnitTestRunner class and ask IntelliJ to run it.

Interface binding in Eclipse

I have the following code in Eclipse(Helios)/STS which runs and prints console output when doing a Run As> Java Application, in spite of obvious compilation issues
public interface ITest{
String func();
}
public static class Test implements ITest{
void printFunc(){
System.out.println("Inside Test Function");
}
}
public static void main(String[] args) {
Test test = new Test();
test.printFunc();
}
Can anyone pinpoint the reasoning behind this Eclipse functioning.
Note: Doing a javac externally obviously fails to compile.
Eclipse's Java compiler is designed to cope with flaky, non-compiling code. It will add whatever stuff is necessary to the code to get it to compile.
See this question What is the difference between javac and the Eclipse compiler?
It might have been that you have coded the class successfully before the errors. Eclipse auto-compiles your file while you are coding. Just then, you happen to have errors.. then you decide to run as Java Application, Eclipse will run the most recent compiled class.
I tried your code, implemented the necessary methods to remove the errors, then removed it again to put back the errors.. sure enough, it printed out "Inside Test Function". I also tried commenting out System.out.println("Inside Test Function"); and it still printed out.
In another try, I created another class, added your code, then run (without implementing the errors to avoid auto-compiling), then it printed out an error..
java.lang.NoSuchMethodError: main
Exception in thread "main"

JUnit #Test expected annotation not working

I've got the following test:
#Test(expected = IllegalStateException.class)
public void testKey() {
int key = 1;
this.finder(key);
}
But JUnit reports, that the test fails, although it throws — as expected — an IllegalStateException.
Do I have to configure something else to make this run?
I run the test now with
#RunWith(Suite.class)
#SuiteClasses(Test.class)
public class TestSuite {
}
like in this question, but am still not getting the desired result.
And when I remove the test prefix I'm still getting an error.
I gotta say that I run these tests with Eclipse, but it's configured to use the JUnit 4 Runner.
The problem was, that the class in which the test was nested was an extension of TestCase. Since this is JUnit 3 style, the annotation didn't work.
Now my test class is a class on its own.
#RunWith(JUnit4.class)
public class MyTestCaseBase extends TestCase
I also had problems with #Test(expected = ...) annotation when I extended TestCase class in my base test. Using #RunWith(JUnit4.class) helped instantly (not an extremely elegant solution, I admit)
i tried this one, and work perfectly as expected.
public class SampleClassTest {
#Test(expected = ArithmeticException.class )
public void lost(){
this.lost(0);
}
private void lost(int i) throws ArithmeticException {
System.out.println(3/i);
}
}
also ensure that junit4 is added as dependancy, # (annotations) are new feature in junit 4.
I faced same issue, solution is simple "Don't extends TestCase class"
No, this JUnit test should work as it is - there is nothing more needed on this side.
What makes you sure that the test throws an IllegalStateException? Is it possible that it gets wrapped into another exception of different type?
Please post the exact failure message from JUnit.
As #duffymo suggested, it is easy to verify what (if any) exception the test really throws.
I had the same problem I just changed my imports statements.
I removed :
import org.junit.jupiter.api.Test;
import junit.framework.TestCase;
and added :
import org.junit.Test;
And it worked fine for me.
This looks correct to me.
Check your assumptions. Are you sure it throws the exception? If what you say is true, removing the expected from the annotation should make it fail.
I'd be stepping through the code with a debugger to see what's going on. I'll assume you have an IDE that will do so, like IntelliJ.
Just tested this under JUnit4: this DO work, test completes successfully. Look if it is a IllegalSelectorException or such.

More Matchers recorded than the expected - Easymock fails from Maven and not from Eclipse

I'm having a strange problem with Easymock 3.0 and JUnit 4.8.2.
The problem only occurs when executing the tests from Maven and not from Eclipse.
This is the unit test (very simple):
...
protected ValueExtractorRetriever mockedRetriever;
...
#Before
public void before() {
mockedRetriever = createStrictMock(ValueExtractorRetriever.class);
}
#After
public void after() {
reset(mockedRetriever);
}
#Test
public void testNullValueExtractor() {
expect(mockedRetriever.retrieve("PROP")).andReturn(null).once();
replay(mockedRetriever);
ValueExtractor retriever = mockedRetriever.retrieve("PROP");
assertNull(retriever);
assertTrue(true);
}
And I get:
java.lang.IllegalStateException: 1 matchers expected, 2 recorded.
The weird thing is that I'm not even using an argument matcher. And that is the only method of the test! and to make it even worst it works from Eclipse and fails from Maven!
I found a few links which didn't provide me with an answer:
Another StackOverflow post
Expected Exceptions in JUnit
If I change the unit test and add one more method (which does use an argument matcher):
#Test
public void testIsBeforeDateOk() {
expect(mockedRetriever.retrieve((String)anyObject())).andReturn(new PofExtractor()).anyTimes();
replay(this.mockedRetriever);
FilterBuilder fb = new FilterBuilder();
assertNotNull(fb);
CriteriaFilter cf = new CriteriaFilter();
assertNotNull(cf);
cf.getValues().add("2010-12-29T14:45:23");
cf.setType(CriteriaType.DATE);
cf.setClause(Clause.IS_BEFORE_THE_DATE);
CriteriaQueryClause clause = CriteriaQueryClause.fromValue(cf.getClause());
assertNotNull(clause);
assertEquals(CriteriaQueryClause.IS_BEFORE_THE_DATE, clause);
clause.buildFilter(fb, cf, mockedRetriever);
assertNotNull(fb);
Filter[] filters = fb.getFilters();
assertNotNull(filters);
assertEquals(filters.length, 1);
verify(mockedRetriever);
logger.info("OK");
}
this last method passes the test but not the other one. How is this possible!?!?!
Regards,
Nico
More links:
"bartling.blogspot.com/2009/11/using-argument-matchers-in-easymock-and.html"
"www.springone2gx.com/blog/scott_leberknight/2008/09/the_n_matchers_expected_m_recorded_problem_in_easymock"
"stackoverflow.com/questions/4605997/3-matchers-expected-4-recorded"
I had a very similar problem and wrote my findings in the link below.
http://www.flyingtomoon.com/2011/04/unclosed-record-state-problem-in.html (just updated)
I believe the problem in on another test that affects your current test. The problem is on another test class and it affects you test. In order to find the place of the real problem, I advice to disable the problematic tests one by one till you notify the failing test.
Actually this is what I did. I disabled the failing tests one by one till I found the problematic test. I found a test that throws an exception and catches by "#extected" annotation without stopping the recording.
We had this problem recently, and it only reared its head when we ran the entire test suite (1100+ test cases). Eventually, I found that I could put a breakpoint on the test that was blowing up, and then step back in the list of tests that Eclipse had already executed, looking for the previous test case that had set up a mock incorrectly.
Our problem turned out to be somebody using EasyMock.anyString() outside of an EasyMock.expect(...) statement. Sure enough, it was done two tests before the one that was failing.
So essentially, what was happening is that the misuse of a matcher outside of an expect statement was poisoning EasyMock's state, and the next time we tried to create a mock, EasyMock would blow up.
I believe the first error message
java.lang.IllegalStateException: 1
matchers expected, 2 recorded.
means your mockedRetriever methods called twice but test expects it was called once. So your Eclipse and Maven's configuration differs.
And I have no reason to reset mock after test. Just keep in mind JUnit creates new class instance for every single test method.
EDITED:
What about the reason why the last test method passed the answer is:
expect(mockedRetriever.retrieve((String)anyObject())).andReturn(new PofExtractor()).anyTimes();
But in your first test method it is:
expect(mockedRetriever.retrieve("PROP")).andReturn(null).once();
as equivalent of:
expect(mockedRetriever.retrieve("PROP")).andReturn(null);

Unrooted Tests

When running all my tests in Eclipse (Eclipse 3.4 'Ganymede'), one test is listed under "Unrooted Tests". I'm using Junit 3.8 and this particular test extends TestCase. I do not see any difference between this test and the other tests. I don't remember seeing this occur in Eclipse 3.3 (Europa).
Clarification:
We haven't moved to JUnit 4.0 yet, so we are not using annotations. I also googled and it seemed like most people were having issues with JUnit 4, but I did not see any solutions. At this point the test passes both locally and in CruiseControl so I'm not overly concerned, but curious.
When I first saw this, though, it was on a failing test that only failed when run with other tests. This led me down the rabbit hole looking for a solution to the "Unrooted" issue that I never found. Eventually I found the culprit in another test that was not properly tearing down.
I agree, it does seem like an Eclipse issue.
Finally I found the solution. The problem is that you are not defining your test cases using annotations but are still doing it the "old way". As soon as you convert over to using annotations you will be able to run one test at a time again.
Here is an example of what a basic test should now look like using annotations:
import static org.junit.Assert.*; // Notice the use of "static" here
import org.junit.Before;
import org.junit.Test;
public class MyTests { // Notice we don't extent TestCases anymore
#Before
public void setUp() { // Note: It is not required to call this setUp()
// ...
}
#Test
public void doSomeTest() { // Note: method need not be called "testXXX"
// ...
assertTrue(1 == 1);
}
}
I was getting the "unrooted tests" error message as well and it went away magically. I believe it was due to the fact that I was using Eclipse with a Maven project. When I added a new method to my Test class and gave it the #Test annotation, it began getting the error message when I tried to run that one method using the "Run as Junit test" menu option; however, once I ran a maven build the unrooted tests message disappeared and I believe that is the solution to the problem in the future.
Run a maven build because it will refresh the class that JUnit is using.
If your class extends TestCase somewhere in its hierarchy, you have to use the JUnit 3 test runner listed in the drop down under run configurations. Using the JUnit 4 runner (the default I believe) causes that unrooted test phenomenon to occur.
I got this error because I renamed my test method and then tried to run the test in Eclipse by clicking on the same run configuration - referring to the old method which now didn't exist.
We solved the problem by making sure our test project was built. We had an issue in the build path which would not allow our test class to be compiled. Once we resolved the build path issue, the test compiled and the "new" method was able to be run. So we can assume that "Unrooted" tests also mean that they don't exist in the compiled binary.
I've never seen this -- but as far as I can tell from skimming Google for a few minutes, this appears as though it could be a bug in Eclipse rather than a problem with your test. You don't have the #Test annotation on the test, I assume? Can you blow the test away and recreate it, and if so do you get the same error?
Another scenario that causes this problem was me blindly copy/pasting a method that requires a parameter. i.e.
import org.junit.Test;
public class MyTest {
#Test
public void someMethod(String param) {
// stuff
}
}
You have a few simple solutions:
define the variable in the specific test method
add it as an instance variable to the test class
create a setup method and annotate it with #Before
For me, it was due to the project got build path issues. My maven dependencies configuration needs to be updated.
I had that problem and putting one "#Test" before the test method solved it!
like this:
#Test
public void testOne() { // ...
assertTrue(1 == 1);
}
These are the two scenarios that the Unrooted errors show up.
If you have missed the annotation #Test before the test.
#Test
public void foo(){
}
If it is a Gwt project and when two mock of the same object are defined. Lets say there is one class Class A and
#GwtMock
private A atest;
#GwtMock
private A a;
Then this will also show a Unrooted test error.
One other thing you can try is to upgrade your version of JUnit to at least 4.12.
I was experiencing this problem for a while with a class that extended one that used #RunWith(Parameterized.class).
After a while, and I'm sorry that I don't know precisely what I did to cause this, the 'Unrooted Tests' message went away, but the test still didn't run correctly. The constructor that should have accepted arguments from the #Parameters method was never getting called; execution jumped straight from #BeforeClass to #AfterClass.
The fix for that problem was to upgrade JUnit from the 4.8.1 it was using, to the latest (4.12). So maybe that could help someone else in the future.
I had the same problem with
java.lang.NoClassDefFoundError: org/hamcrest/SelfDescribing
you need the jar hamcrest.
same question 14539072: java.lang.NoClassDefFoundError: org/hamcrest/SelfDescribing
I could the fix the issue by shifting from TestRunner ver 4.0 to 3 in run configurations for the individual test method.
Do not extend junit.framework.TestCase in your test class with junit1.4 and this should solve the problem
You are using Hamcrest? or another library to help in your test?. You are not using
import static org.junit.Assert.*;
Check if in your test you use:
import static org.hamcrest.MatcherAssert.assertThat;
or other assert isn´t JUnit assert.
It turned out to be that my build path had some error...some jars were missing.
I reconfigured build path and it worked!
For me the problem was, that an exception was thrown in the #BeforeClass or #AfterClass methods. This will also cause tests to be categorized as unrooted.
I got this error with the test method name as "test"
#Test
public void test() {
// ... assertTrue(1 == 1);
}
I renamed the method and it worked
I ran into this problem by not also declaring the test to be static.
Maybe it's just a logical confusion about the goal of the method. Let's remember:
E.g. correct tagged test method:
#Test
#Transactional
#Rollback(true)
public void testInsertCustomer() {
(...)
}
-With Eclipse Junit plugin, You can run that test method using context menu over the method (E.g. at package explorer expanding the class and methods and selecting "testInsertCustomer()" method and from that item selecting "Run as >> JUnit test").
If you forgot "#Test" tag, or simply the method is not a test, but a (private or not) common method for using as utility for the other tests (e.g. "private fillCustomerObject()"), then the method does not require "#Test" tag, and simply you can not run it as a JUnit test!
It's easy that you could create a utility method and later you forgot the real goal of that method, so if you try to run it as a test, JUnit will shout "Unrooted Tests".
For me this problem was created by a real-time exception thrown in the #AfterClass method (take a look here for documentation):
Basically all the test methods succeeded but at the end of the class this method was failing. Therefore all the tests seems fine but there was on my Eclipse an additional "unrooted test" failed.
I got these errors for a maven project. I rebuild the project with mvn clean install.And the issue was solved
It actually told me there is a test with annotation: #RunWith(MockitoJUnitRunner.class)

Categories