Question
Why does NetBeans report 'Cannot find symbol assertEquals' and '@Test' when writing unit tests?
package calculator;
import org.junit.Assert.*;
import org.junit.Test;
public class UnitTests{
@Test
public void checkAdd(){
assertEquals(2, Calculator.rpnCalc(" 2 3 + "));
}
}
Answer
When writing unit tests in Java with JUnit, encountering the error 'Cannot find symbol assertEquals' usually indicates a problem with your import statements. This error can arise if the methods or annotations from JUnit are not correctly imported, or if the static imports are missing.
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class UnitTests{
@Test
public void checkAdd(){
assertEquals(2, Calculator.rpnCalc(" 2 3 + "));
}
}
Causes
- Missing import for the static method assertEquals.
- Not importing the JUnit Test annotation.
- Using an incorrect version of JUnit that does not support these methods.
Solutions
- Add a static import for assertEquals by including 'import static org.junit.Assert.assertEquals;'.
- Ensure you are using the correct JUnit version (like JUnit 4 or higher).
- Import the Test annotation correctly with 'import org.junit.Test;'.
- Check your project setup to ensure JUnit library is included in your classpath.
Common Mistakes
Mistake: Not importing the static method assertEquals properly.
Solution: Use 'import static org.junit.Assert.assertEquals;' to import the assertEquals method.
Mistake: Not including the required JUnit imports.
Solution: Ensure to import both 'import org.junit.Test;' and 'import static org.junit.Assert.*;' correctly.
Helpers
- JUnit assertEquals issue
- NetBeans unit testing
- Cannot find symbol assertEquals
- unit test annotation error
- Java JUnit tutorial
- Java testing with JUnit