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 Overflow
🌐
GitHub
github.com › junit-team › junit4 › issues › 1430
NullPointerException · Issue #1430 · junit-team/junit4
This code results in a nullpointer exception inside of junit, as the surrounding code is static. The stacktrace: java.lang.NullPointerException at xxx.IsCustomer.apply(IsCustomer.java:21) at xxx.IsCustomerTest.testNotFound(IsCustomerTest.java:36) at sun.reflect.NativeMethodAccessorImpl.inv...
Author   junit-team
Top answer
1 of 2
5

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 ) { ...
2 of 2
1

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);
Discussions

java - JUnit testing for assertEqual NullPointerException - Stack Overflow
I am not sure why the test case doesn't have an output of true. Both cases should give a NullPointerException. I've tried doing this (Not exactly the same but it gives and output of true) : S... More on stackoverflow.com
🌐 stackoverflow.com
java - JUNIT Null Pointer Exception - Stack Overflow
it's my first time using JUNIT and I literally cannot get it to work. I've got a person class, in which has firstName and lastName, and a test class in which I need to test the methods. Everytime I More on stackoverflow.com
🌐 stackoverflow.com
November 14, 2013
Junit test fail for the java.lang.NullPointerException - Stack Overflow
I work to test a class with the Junit and I get an NullPointerException. The class I would like to test is provided below, @Component public class EmailageConnector { private static final ... More on stackoverflow.com
🌐 stackoverflow.com
May 28, 2019
spring - How to fix Null Pointer Exception in Junit test? - Stack Overflow
Communities for your favorite technologies. Explore all Collectives · Ask questions, find answers and collaborate at work with Stack Overflow for Teams More on stackoverflow.com
🌐 stackoverflow.com
August 23, 2019
🌐
Reddit
reddit.com › r/javahelp › junit - test fails (null pointer exception) for no apparent reason
r/javahelp on Reddit: JUnit - Test fails (null pointer exception) for no apparent reason
April 26, 2018 -

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.

🌐
Eviltester
eviltester.com › 2017 › 08 › faq-null-pointer-exception.html
Why does my code throw a null pointer exception? - common reason - EvilTester.com
TLDR; check that you haven’t redeclared a field as a variable in a setup method FAQ - why does my code throw a null pointer exception - common reason #1 Redeclaration Using @BeforeClass or @Before can setup data for use in tests Any ‘variables’ we instantiate need to be ‘fields’ rather than variables We want to instantiate them in the setup method rather than redeclare them
🌐
Coderanch
coderanch.com › t › 96059 › engineering › handle-NullPointerException-tests
How to handle NullPointerException in your tests... (Testing forum at Coderanch)
Now I want to know is there any better way than putting this method call in a try/catch block and check to see myException.getClass().getName() == java.lang.NullPointerException" or myException instanceof NullPointerException or this is the best way in your opinion. Of course I could use a mock object (e.g. using easyMock) and expect my desirable Exception but I prefer using a real one instead of playing with mocks in this case. Your ideas are appreciated ... When using JUnit 4, you can use @Test(expected=NullPointerException.class) With JUnit 3, using the try-catch approach actually is the most common way.
Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 57628837 › how-to-fix-null-pointer-exception-in-junit-test
spring - How to fix Null Pointer Exception in Junit test? - Stack Overflow
August 23, 2019 - 0 Junit test fail for the java.lang.NullPointerException · Is the surface of Mars or the Moon mostly (or relatively) homogeneous, unlike the Earth? tac-command is it a bug or a misinterpretation of the manual? Do the constructible lines and circles (not merely their intersections) cover the plane?
🌐
Coderanch
coderanch.com › t › 739460 › frameworks › NullPointerException-run-unit-test-Spring
Getting NullPointerException when run unit test using Spring boots, JUnit 5 and Mockito (Spring forum at Coderanch)
February 16, 2021 - @RestController @RequestMapping("/user") public class UserRestController { @Autowired UserService userService; @PostMapping(path="save", consumes= {MediaType.APPLICATION_JSON_VALUE}, produces= {MediaType.APPLICATION_JSON_VALUE}) public String createUser(@RequestBody User user) { User userResponse = userService.createUser(user); System.out.println("userResponse ..: " + userResponse ); // These is null when Test run return String.valueOf(userResponse.getId()); } } // end UserController @Service public class UserServiceImpl implements UserService { @Autowired private UserRepository userRepository
🌐
JUnit
junit.org › junit4 › javadoc › latest › org › junit › rules › ExpectedException.html
ExpectedException (JUnit API)
@Test public void throwsExceptionWhoseCauseCompliesWithMatcher() { NullPointerException expectedCause = new NullPointerException(); thrown.expectCause(is(expectedCause)); throw new IllegalArgumentException("What happened?", cause); }
🌐
GitHub
github.com › spring-projects › spring-restdocs › issues › 490
Nullpointer Exception when using JUnit 5 @Nested tests · Issue #490 · spring-projects/spring-restdocs
March 14, 2018 - Hello Spring REST Docs Team! It seems that JUnit 5's @Nested tests don't work with auto-configured Spring REST Docs. Executing the following simple test class will result in a NullPointerException: package example; import org.junit.jupit...
Author   spring-projects
🌐
Adobe Experience League
experienceleaguecommunities.adobe.com › t5 › adobe-experience-manager › junit-5-throws-java-lang-nullpointerexception-cannot-invoke-quot › m-p › 432340
Solved: Re: JUnit 5 throws java.lang.NullPointerException:... - Adobe Experience League Community - 432235
November 29, 2021 - I have below ServletTest to test my ExampleServlet. Below Error is thrown when I ran mvn clean install command · java.lang.NullPointerException: Cannot invoke "org.apache.sling.api.resource.Resource.getPath()" because "parent" is null
🌐
GitHub
github.com › oracle › visualvm › issues › 104
NullPointerException when launching a JUnit4 test with coverage · Issue #104 · oracle/visualvm
August 28, 2018 - Regular Java applications as well as TestNG tests are not affected by this problem. The issue can be worked around by uninstalling the VisualVM launcher. This is a known issue -- see, for example, Coverage As -> JUnit Test in Eclipse Oxygen reports NullPointerException.
Author   oracle
🌐
Coderanch
coderanch.com › t › 684710 › engineering › null-pointer-error-JUnit-test
Getting null pointer error in JUnit test (Testing forum at Coderanch)
September 14, 2017 - Testcase: testProcessEmployees(onplanusermodule.OnPlanUserModuleTest): Caused an ERROR null java.lang.NullPointerException at onplanusermodule.TimeSeries.getTimeSeries(TimeSeries.java:28) at onplanusermodule.OnPlanUserModule.ProcessEmployees(OnPlanUserModule.java:58) at onplanusermodule.OnPlanUserModuleTest.testProcessEmployees(OnPlanUserModuleTest.java:171) I tried code below (lines 26-28)which I thought would intialize the time series but still get similar error I decided this would be better than using the constructor.