You never initialize the filter field in the test class
NoiseFilter filter;
SensorData dataSet;
@Before
public void setUp() throws Exception {
this.dataSet = new SensorData();
dataSet.setFilter(filter);
}
so it is null here and that reference propagates to the SensorData object you are testing.
public void setFilter(NoiseFilter filterVar) {
this.filter = filterVar;
}
filterVar is null when you call the above.
You have to initialize it with an implementation of your interface, such as your AveragingFilter:
@Before
public void setUp() throws Exception {
this.filter = new AveragingFilter(); // or something like it
this.dataSet = new SensorData();
dataSet.setFilter(filter);
}
Also, you are testing for null in a few places using this pattern:
if( x.equals( null ) ) {...
This will not work, because this is calling the equals(Object) method on the object x. In Java, null does not have any methods. You always have to check for null against its identity, using the == operator. Your examples should read:
if( x == null ) { ...
Answer from Sotirios Delimanolis on Stack OverflowYou never initialize the filter field in the test class
NoiseFilter filter;
SensorData dataSet;
@Before
public void setUp() throws Exception {
this.dataSet = new SensorData();
dataSet.setFilter(filter);
}
so it is null here and that reference propagates to the SensorData object you are testing.
public void setFilter(NoiseFilter filterVar) {
this.filter = filterVar;
}
filterVar is null when you call the above.
You have to initialize it with an implementation of your interface, such as your AveragingFilter:
@Before
public void setUp() throws Exception {
this.filter = new AveragingFilter(); // or something like it
this.dataSet = new SensorData();
dataSet.setFilter(filter);
}
Also, you are testing for null in a few places using this pattern:
if( x.equals( null ) ) {...
This will not work, because this is calling the equals(Object) method on the object x. In Java, null does not have any methods. You always have to check for null against its identity, using the == operator. Your examples should read:
if( x == null ) { ...
Your setUp()method does not create a filter.
It creates an instance of SensorData and then passes a null value to setFilter. When getFilteredResult() is called later on it runs into a NPE.
Added after commenting:
Anonymous class:
filter = new NoiseFilter() {
public double getBestMesurement(ArrayList<Double> samples) {
return 100; // or do something else
}
}
dataSet.setFilter(filter);
with Mockito:
import static org.mockito.Mockito.*;
import static org.mockito.Matchers.*
// ...
filter = Mockito.mock( NoiseFilter.class );
when( filter.getBestMesurement( anyListOf( Double.class ) ) ).thenReturn( 100.0 )
dataSet.setFilter(filter);
java - JUnit testing for assertEqual NullPointerException - Stack Overflow
java - JUNIT Null Pointer Exception - Stack Overflow
Junit test fail for the java.lang.NullPointerException - Stack Overflow
spring - How to fix Null Pointer Exception in Junit test? - Stack Overflow
Issue
I have a @Before method that initialises an array of objects to be used in my @Test methods. The tests always fail, and I have verified that they work if the array is initialised within the @Test methods themselves. Can anyone point out where the issue lies here? Included below is the relevant code and stack trace.
MainTest.java
class MainTest {
private Lord[] baratheons;
private Lord[] starks;
//Setup & Teardown
@Before
public void setUp() throws Exception {
baratheons = new Lord[3];
baratheons[0] = new Lord("Robert", 15);
baratheons[1] = new Lord("Renly", -5);
baratheons[2] = new Lord("Stannis", 30);
System.out.println("Baratheons initialised!");
starks = new Lord[3];
starks[0] = new Lord("Robb", -60);
starks[1] = new Lord("Eddard", 0);
starks[2] = new Lord("Jon", 90);
System.out.println("Starks initialised!");
}
//Tests
@Test
public void testGratefulLord() {
int x = baratheons[0].getRelationship(); //THIS IS LINE 36
baratheons[0].giveFief();
assertEquals(baratheons[0].getRelationship(), (x+10));
}Stack Trace
java.lang.NullPointerException
at mainPackage.MainTest.testGratefulLord\([MainTest.java:36](https://MainTest.java:36)\) at sun.reflect.NativeMethodAccessorImpl.invoke0\(Native Method\)
Edit: So I can verify now that the setup method is not being called. Does anyone know why this may be the case?
EDIT 2: I changed @Before to @BeforeEach and the tests now pass. This is because @Before is what the tag was called in JUnit 4, and @BeforeEach is the equivalent in JUnit 5, which I am using.
I hope my idiocy proves useful to people reading this in the future.
I believe you want to use fail here:
@Test(expected=NullPointerException.class)
public void testNullInput() {
fail(nullString.indexOf(3));
}
Make sure to add import static org.junit.Assert.fail; if you need to.
In Java 8 and JUnit 5 (Jupiter) we can assert for exceptions as follows.
Using org.junit.jupiter.api.Assertions.assertThrows
public static < T extends Throwable > T assertThrows(Class< T > expectedType, Executable executable)
Asserts that execution of the supplied executable throws an exception of the expectedType and returns the exception.
If no exception is thrown, or if an exception of a different type is thrown, this method will fail.
If you do not want to perform additional checks on the exception instance, simply ignore the return value.
@Test
public void itShouldThrowNullPointerExceptionWhenBlahBlah() {
assertThrows(NullPointerException.class,
()->{
//do whatever you want to do here
//ex : objectName.thisMethodShoulThrowNullPointerExceptionForNullParameter(null);
});
}
That approach will use the Functional Interface Executable in org.junit.jupiter.api.
Refer :
- http://junit.org/junit5/docs/current/user-guide/#writing-tests-assertions
- http://junit.org/junit5/docs/5.0.0-M2/api/org/junit/jupiter/api/Executable.html
- http://junit.org/junit5/docs/5.0.0-M4/api/org/junit/jupiter/api/Assertions.html#assertThrows-java.lang.Class-org.junit.jupiter.api.function.Executable-
This is the right way to do it:
@Before
public void setUp() {
p1 = new Person ("Thomas", "Brown");
}
You have 2 problems in your code.
public PersonTest() {
Person p1 = new Person ("Thomas", "Brown");
}
This creates a local variable and your field p1 stays null.
The second is that in your setUp method you do not initialize p1.
The method you annotate with @Before will run before every test to you should put the initialization there. I also suggest to use more descriptive names so you should change p1 to target or something like that.
Edit: For your set... methods you can do something like this:
public class PersonTest {
private static final String TEST_FIRST_NAME = "some name";
Person target;
// ...
@Test
public void testSetFirstName() {
target.setFirstName(TEST_FIRST_NAME);
Assert.assertEquals(target.getFirstName(), TEST_FIRST_NAME);
}
}
At that point you can assume that getFirstName works since you have a test for it as well.
A sidenote: I think you don't have to test getters and setters as long as you generate them with Eclipse. It is just unnesessary.
Change
Person p1 = new Person ("Thomas", "Brown"); //this is local variable
to
p1 = new Person ("Thomas", "Brown");// and this will use the instance variable
Use
@Test(expected=NullPointerException.class)
instead of
@Test
and the error-message will go away.
Assuming you want to test, that your method throws a NullPointerException as expected, then your test case has to assume that the control flow goes into your catch-block and you do nothing there which causes the test to become green. If instead the flow continues beyond the call without getting an exception, you should explicitely fail and cause the test to become red.
greenLeftArrow is not initialized to a value (it's automatically initialized to null) so calling greenLeftArrow.isOn() in the PhaseOneInitialization method will throw a NullPointerException.
You should initialize greenLeftArrow object first like you did for example greenLight. You cannot call methods on not initialized objects.
You can also use assertTrue or assertFalse to simplify your code.