简体   繁体   中英

Could not find class in JUnit 4.11

First of all, I've looked at all of the similar questions on stack overflow and nothing has worked for me yet. Just trying to get JUnit to work with a simple example from the book JUnit in Action 2nd Edition by Peter Tahchiev.

Calculator.java

public class Calculator {
    public double add(double number1, double number2) {
        return number1 + number2;
    }
}

CalculatorTest.java

import static org.junit.Assert.assertEquals;
import org.junit.Test;

public class CalculatorTest {

    @Test
    public void testAdd() {
        Calculator calc = new Calculator();
        double result = calc.add(1,1);
        assertEquals(2, result,0);
    }
}

My folder: 当前文件夹

I compile with:

javac -cp junit-4.11.jar *.java

My folder after compiling: 编译后的当前文件夹

I Try to Run Test with:

java -cp junit-4.11.jar;hamcrest-core-1.3.jar;. org.junit.runner.JUnitCore CalculatorTest

This is my output:

产量

When I try to run the individual classes the jre finds them but throws a no main method error which is expected:

java Calculator
java CalculatorTest

Outputs(which were expected, but it found the classes): 错误1错误2

Any ideas how I can get JUnit/whatever it is to behave?

[EDIT]
I run all commands in C:\\Users\\Zach\\Documents\\docs\\Code\\JUnit
The screenshots above are of the same folder.
I'm using jdk1.7.0_45 and jre7
I'm using Windows 7 Professional N 64 - bit

I ran the java command using -verbose:class and there were no errors except the one on line 426 which is seen below: 详细错误

Fascinating. Anyways, it appears you have junit-4.11.jar in lib/ext in your JRE. This location takes preference over the classpath and classes loaded in this directory are loaded in a separate classloader.

That lib/ext classloader can't see the class loaded by the classpath classloader and thus JUnit can't see your code. If you are using Junit from the command line in this fashion it is probably best not to put the jar in your lib/ext folder. If you were running it programmatically (eg JUnitCore.runClasses(...)) then you could load your classes using the normal classloader and pass them to JUnit in the secluded classloader and all would be good.

So, short answer is probably to remove the junit jar from the lib/ext folder provided you know why it was in there in the first place and that reason is no longer valid.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM