The solution is simple. You mocked a class customerDataRepository but did not instruct it the mock what to do if the corresponding method is called. Mockito mocks then default back on doing nothing by method call and if there is a return value return null. Since your returned customerData is null you get your NPE when calling on this object. In your case this is in the error case that you get by calling getCustomerId().

To solve this issue simply instruct your mock

@Test
void removeCustomerDataWhenConsentIsNotGiven() {
   CustomerData customerDataTest = customerData;
   //when
   Mockito.when(customerDataRepository.findCustomerByDialogId(Mockito.any())).thenReturn(new CustomerData()); // <-- Add this line
   customerDataService.giveConsent(false,22L);
   //then 
   verify(customerDataRepository,times(1)).save(customerDataTest);
}

you can obviously replace Mockito.any() with Mockito.anyInt() or 42 and new CustomerData() with a object you previously created. I think you get the idea ;)

Answer from GJohannes on Stack Overflow
Top answer
1 of 2
5

The solution is simple. You mocked a class customerDataRepository but did not instruct it the mock what to do if the corresponding method is called. Mockito mocks then default back on doing nothing by method call and if there is a return value return null. Since your returned customerData is null you get your NPE when calling on this object. In your case this is in the error case that you get by calling getCustomerId().

To solve this issue simply instruct your mock

@Test
void removeCustomerDataWhenConsentIsNotGiven() {
   CustomerData customerDataTest = customerData;
   //when
   Mockito.when(customerDataRepository.findCustomerByDialogId(Mockito.any())).thenReturn(new CustomerData()); // <-- Add this line
   customerDataService.giveConsent(false,22L);
   //then 
   verify(customerDataRepository,times(1)).save(customerDataTest);
}

you can obviously replace Mockito.any() with Mockito.anyInt() or 42 and new CustomerData() with a object you previously created. I think you get the idea ;)

2 of 2
1

Assuming that you have just corrected method names before posting it to Stackoverflow, and method you are calling in the test: giveConsent is, actually, the same method as methodTotest of the CustomerDataService.

Before calling customerDataService.giveConsent(false,22L);, you need to configure you repository to return some test (not null! or mocked) customerData entity:

when(customerDataRepository.findCustomerByDialogId(22L)).thenReturn(customerDataTest);
customerDataService.giveConsent(false,22L);

Note: since you are passing false as 1st variable, you will get to this branch of code

    if (!consent) {  
      customerDataRepository.deleteById(customer.getCustomerId());
    }

And in the test you are expecting save() method to be called, so the test will fail.

๐ŸŒ
Coderanch
coderanch.com โ€บ t โ€บ 750685 โ€บ engineering โ€บ Null-Pointer-exception-Unit-Test
Null Pointer exception in Unit Test (Testing forum at Coderanch)
java.lang.NullPointerException: Cannot invoke "com.example.onlinehotelbookingsystem.service.RoomService.findByHotelId(java.lang.Long)" because "this.roomService" is null at com.example.onlinehotelbookingsystem.service.impl.AccommodationServiceImpl.lambda$findById$0(AccommodationServiceImpl.java:56) at java.base/java.util.Optional.map(Optional.java:260) at com.example.onlinehotelbookingsystem.service.impl.AccommodationServiceImpl.findById(AccommodationServiceImpl.java:52) at com.example.onlinehotelbookingsystem.service.impl.AccommodationServiceImplTest.whenFindById_verifyThatIsNotNull(Accommoda
Discussions

java - What is a NullPointerException, and how do I fix it? - Stack Overflow
What are Null Pointer Exceptions (java.lang.NullPointerException) and what causes them? What methods/tools can be used to determine the cause so that you stop the exception from causing the progra... More on stackoverflow.com
๐ŸŒ stackoverflow.com
java - Getting NullPointerException in JUNit testing - Stack Overflow
I am trying to do some JUnit testing for a college assignment but I get an error every time I try to run my tests. When I first created my file it worked fine but after I restarted my Intellij this More on stackoverflow.com
๐ŸŒ stackoverflow.com
Getting nullpointer exception when updated to junit5 in serenity bdd tests
What happened? I am using serenity-bdd with selenium. Currently we need to upgrade selenium 3 to selenium 4.And serenity is updated to 4.0.18. While running the test using maven command "mvn c... More on github.com
๐ŸŒ github.com
5
November 1, 2023
spring boot - JUnit - java.lang.NullPointerException: Cannot invoke "..." because "this.modelMapper" is null - Stack Overflow
I've been learning Java for about 4 months, so please excuse basic mistakes. I'm trying to unit test a method from my Service layer: @Override @Transactional public List More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
Fix the bugs
fixthebugs.com โ€บ home โ€บ fixed bugs โ€บ junit: java.lang.nullpointerexception: cannot invoke โ€œ[ljava.lang.class;.clone()โ€ because โ€ .parametertypesโ€ is null
JUnit: java.lang.NullPointerException: Cannot invoke "[Ljava.lang.Class;.clone()" because " .parameterTypes" is null - Fix the bugs
March 5, 2024 - java.lang.NullPointerExceptionjava.lang.NullPointerException: Cannot invoke "[Ljava.lang.Class;.clone()" because " .parameterTypes" is nullJUnit ยท Problem: If you are launching JUnit test and returns next error:
๐ŸŒ
OneUptime
oneuptime.com โ€บ home โ€บ blog โ€บ how to handle 'cannot invoke method on null' errors
How to Handle 'Cannot invoke method on null' Errors
December 22, 2025 - NullPointerException is preventable with defensive coding practices. Use Optional for values that might not exist, validate inputs at boundaries, use constructor injection with required dependencies, and return empty collections instead of null. Modern Java's helpful NPE messages make debugging easier, but prevention is better than cure.
Top answer
1 of 12
4227

There are two overarching types of variables in Java:

  1. Primitives: variables that contain data. If you want to manipulate the data in a primitive variable you can manipulate that variable directly. By convention primitive types start with a lowercase letter. For example variables of type int or char are primitives.

  2. References: variables that contain the memory address of an Object i.e. variables that refer to an Object. If you want to manipulate the Object that a reference variable refers to you must dereference it. Dereferencing usually entails using . to access a method or field, or using [ to index an array. By convention reference types are usually denoted with a type that starts in uppercase. For example variables of type Object are references.

Consider the following code where you declare a variable of primitive type int and don't initialize it:

int x;
int y = x + x;

These two lines will crash the program because no value is specified for x and we are trying to use x's value to specify y. All primitives have to be initialized to a usable value before they are manipulated.

Now here is where things get interesting. Reference variables can be set to null which means "I am referencing nothing". You can get a null value in a reference variable if you explicitly set it that way, or a reference variable is uninitialized and the compiler does not catch it (Java will automatically set the variable to null).

If a reference variable is set to null either explicitly by you or through Java automatically, and you attempt to dereference it you get a NullPointerException.

The NullPointerException (NPE) typically occurs when you declare a variable but did not create an object and assign it to the variable before trying to use the contents of the variable. So you have a reference to something that does not actually exist.

Take the following code:

Integer num;
num = new Integer(10);

The first line declares a variable named num, but it does not actually contain a reference value yet. Since you have not yet said what to point to, Java sets it to null.

In the second line, the new keyword is used to instantiate (or create) an object of type Integer, and the reference variable num is assigned to that Integer object.

If you attempt to dereference num before creating the object you get a NullPointerException. In the most trivial cases, the compiler will catch the problem and let you know that "num may not have been initialized," but sometimes you may write code that does not directly create the object.

For instance, you may have a method as follows:

public void doSomething(SomeObject obj) {
   // Do something to obj, assumes obj is not null
   obj.myMethod();
}

In which case, you are not creating the object obj, but rather assuming that it was created before the doSomething() method was called. Note, it is possible to call the method like this:

doSomething(null);

In which case, obj is null, and the statement obj.myMethod() will throw a NullPointerException.

If the method is intended to do something to the passed-in object as the above method does, it is appropriate to throw the NullPointerException because it's a programmer error and the programmer will need that information for debugging purposes.

In addition to NullPointerExceptions thrown as a result of the method's logic, you can also check the method arguments for null values and throw NPEs explicitly by adding something like the following near the beginning of a method:

// Throws an NPE with a custom error message if obj is null
Objects.requireNonNull(obj, "obj must not be null");

Note that it's helpful to say in your error message clearly which object cannot be null. The advantage of validating this is that 1) you can return your own clearer error messages and 2) for the rest of the method you know that unless obj is reassigned, it is not null and can be dereferenced safely.

Alternatively, there may be cases where the purpose of the method is not solely to operate on the passed in object, and therefore a null parameter may be acceptable. In this case, you would need to check for a null parameter and behave differently. You should also explain this in the documentation. For example, doSomething() could be written as:

/**
  * @param obj An optional foo for ____. May be null, in which case
  *  the result will be ____.
  */
public void doSomething(SomeObject obj) {
    if(obj == null) {
       // Do something
    } else {
       // Do something else
    }
}

Finally, How to pinpoint the exception & cause using Stack Trace

What methods/tools can be used to determine the cause so that you stop the exception from causing the program to terminate prematurely?

Sonar with find bugs can detect NPE. Can sonar catch null pointer exceptions caused by JVM Dynamically

Now Java 14 has added a new language feature to show the root cause of NullPointerException. This language feature has been part of SAP commercial JVM since 2006.

In Java 14, the following is a sample NullPointerException Exception message:

in thread "main" java.lang.NullPointerException: Cannot invoke "java.util.List.size()" because "list" is null

List of situations that cause a NullPointerException to occur

Here are all the situations in which a NullPointerException occurs, that are directly* mentioned by the Java Language Specification:

  • Accessing (i.e. getting or setting) an instance field of a null reference. (static fields don't count!)
  • Calling an instance method of a null reference. (static methods don't count!)
  • throw null;
  • Accessing elements of a null array.
  • Synchronising on null - synchronized (someNullReference) { ... }
  • Any integer/floating point operator can throw a NullPointerException if one of its operands is a boxed null reference
  • An unboxing conversion throws a NullPointerException if the boxed value is null.
  • Calling super on a null reference throws a NullPointerException. If you are confused, this is talking about qualified superclass constructor invocations:
class Outer {
    class Inner {}
}
class ChildOfInner extends Outer.Inner {
    ChildOfInner(Outer o) { 
        o.super(); // if o is null, NPE gets thrown
    }
}
  • Using a for (element : iterable) loop to loop through a null collection/array.

  • switch (foo) { ... } (whether its an expression or statement) can throw a NullPointerException when foo is null.

  • foo.new SomeInnerClass() throws a NullPointerException when foo is null.

  • Method references of the form name1::name2 or primaryExpression::name throws a NullPointerException when evaluated when name1 or primaryExpression evaluates to null.

    a note from the JLS here says that, someInstance.someStaticMethod() doesn't throw an NPE, because someStaticMethod is static, but someInstance::someStaticMethod still throw an NPE!

* Note that the JLS probably also says a lot about NPEs indirectly.

2 of 12
972

NullPointerExceptions are exceptions that occur when you try to use a reference that points to no location in memory (null) as though it were referencing an object. Calling a method on a null reference or trying to access a field of a null reference will trigger a NullPointerException. These are the most common, but other ways are listed on the NullPointerException javadoc page.

Probably the quickest example code I could come up with to illustrate a NullPointerException would be:

public class Example {

    public static void main(String[] args) {
        Object obj = null;
        obj.hashCode();
    }

}

On the first line inside main, I'm explicitly setting the Object reference obj equal to null. This means I have a reference, but it isn't pointing to any object. After that, I try to treat the reference as though it points to an object by calling a method on it. This results in a NullPointerException because there is no code to execute in the location that the reference is pointing.

(This is a technicality, but I think it bears mentioning: A reference that points to null isn't the same as a C pointer that points to an invalid memory location. A null pointer is literally not pointing anywhere, which is subtly different than pointing to a location that happens to be invalid.)

Find elsewhere
๐ŸŒ
GitHub
github.com โ€บ serenity-bdd โ€บ serenity-core โ€บ issues โ€บ 3309
Getting nullpointer exception when updated to junit5 in serenity bdd tests ยท Issue #3309 ยท serenity-bdd/serenity-core
November 1, 2023 - @test and @tag is from junit jupiter api ยท Expected a success test. But the error which i get is ยท [ERROR] com.xxx.xxx.UJTest.UserJourneyPart1_HierarchyUploadAndLogin Time elapsed: 0.022 s <<< ERROR! java.lang.NullPointerException: Cannot invoke "com.allianz.frp.steps.LoginSteps.loginAsGroupManager()" because "this.loginSteps" is null at gui.test@1.0.2-SNAPSHOT/com.xxx.xxx.UJTest.UserJourneyPart1_HierarchyUploadAndLogin(UJTest.java:71) (the only line inside the method) Note: The same test ran well in ```xml <junit.version>4.13.2</junit.version> ### Serenity BDD version 4.0.18 ### JDK version 17 ### Execution environment Currently executing in local windows.
Author: serenity-bdd
๐ŸŒ
JetBrains
youtrack.jetbrains.com โ€บ issue โ€บ KT-53579 โ€บ cannot-invoke-function-because-the-return-value-of-X-is-null.
cannot invoke function because the return value of X is null. : KT-53579
java.lang.NullPointerException: Cannot invoke "com.vanniktech.playground.kmp.AppVersion.getVersion()" because the return value of "com.vanniktech.playground.kmp.DefaultFeatureFlag.getSince()" is null at com.vanniktech.playground.kmp.FeatureFlagKt.asFeatureFlag(FeatureFlag.kt:20) at com.vanniktech.playground.kmp.RealFeatureFlagService.isEnabled(RealFeatureFlagService.kt:12) at com.vanniktech.playground.kotlin.RealFeatureFlagServiceTest.isEnabled(RealFeatureFlagServiceTest.kt:19) at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104) at java.base
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 71653419 โ€บ junit-java-lang-nullpointerexception-cannot-invoke-because-this-modelm
spring boot - JUnit - java.lang.NullPointerException: Cannot invoke "..." because "this.modelMapper" is null - Stack Overflow
Copy // JUnit test for getStudentList() @Test @DisplayName("getStudentList()") public void givenStudentList_whenGettingList_thenReturnList() { // given -precondition BDDMockito.given(studentDao.getStudentList()) .willReturn(List.of(newStudentOne, newStudentTwo)); // when - behaviour that we are going to test List<StudentDto> studentList = studentService.getStudentList(); // then - verify the output assertAll( () -> org.assertj.core.api.Assertions.assertThat(studentList).isNotNull(), () -> org.assertj.core.api.Assertions.assertThat(studentList).size().isEqualTo(2) );
๐ŸŒ
GitHub
github.com โ€บ junit-team โ€บ junit4 โ€บ issues โ€บ 1430
NullPointerException ยท Issue #1430 ยท junit-team/junit4
March 15, 2017 - 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.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(Frame
Author: junit-team
๐ŸŒ
Javatpoint
javatpoint.com โ€บ how-to-avoid-null-pointer-exception-in-java
How to avoid null pointer exception in Java - Javatpoint
How to avoid null pointer exception in Java with java tutorial, features, history, variables, object, programs, operators, oops concept, array, string, map, math, methods, examples etc.
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);
๐ŸŒ
Reddit
reddit.com โ€บ r/javahelp โ€บ exception in thread "main" java.lang.nullpointerexception: cannot invoke "java.net.url.toexternalform()" because "location" is null
r/javahelp on Reddit: Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.net.URL.toExternalForm()" because "location" is null
May 18, 2023 -

https://pastebin.com/vtcMwSRn

So I am currently going crazy trying to get images to load when you export it to a .jar file. Before I was just using, "new imageicon("picturepath")"

As you can see from lines 30-34.

Then I found out that doesn't carry over when you make the project into a .jar file, okay cool. So I found out that you want to use, "getResource" okay cool got it. Try that and now I get the error in the title. when that location isn't fucking null so that's horse shit. I've tried every variation of that path. I have tried moving my images folder all over the project; from inside the src folder, where it is now, to just in the main project folder, etc. I don't know why it isn't happy.

Exception in thread "main" java.lang.NullPointerException: Cannot invoke 
"java.net.URL.toExternalForm()" because "location" is null
at java.desktop/javax.swing.ImageIcon.<init>(ImageIcon.java:234)
at LaunchPage.<init>(LaunchPage.java:25)
at Main.main(Main.java:5)
Top answer
1 of 2
3
When you use getResource() (on a class or a classloader) the file is assumed to be located on the classpath, paths may be relative or absolute, but on the classpath. For example, MyClass.getClass().getResource("myfile"), will look for myfile in the same packege as MyClass (the file are assumed to be located in the same folder as "MyClass.class" when the program runs). You may read more about it at: https://www.baeldung.com/java-class-vs-classloader-getresource https://docs.oracle.com/javase/8/docs/technotes/guides/lang/resources.html (it is old, but still relevant)
2 of 2
1
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
๐ŸŒ
DigitalOcean
digitalocean.com โ€บ community โ€บ tutorials โ€บ java-lang-nullpointerexception
Java NullPointerException - Detect, Fix, and Best Practices | DigitalOcean
August 3, 2022 - Technical tutorials, Q&A, events โ€” This is an inclusive place where developers can find or lend support and discover new ways to contribute to the community.
๐ŸŒ
Reddit
reddit.com โ€บ r/javahelp โ€บ need some help debugging. exception in thread "main" java.lang.nullpointerexception: cannot invoke "object.equals(object)" because "this.items[i]" is null
r/javahelp on Reddit: Need some help debugging. Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Object.equals(Object)" because "this.items[i]" is null
November 2, 2023 -
public class ArraySet<T> {
    private T[] items;
    private int size;

    public ArraySet() {
        items = (T[]) new Object[100];
        size = 0;
    }

    public void add(T value) {
        for (int i = 0; i < size; i++) {
            if (items[i] == value) {
                return;
            }
        }
        items[size + 1] = value;
        size ++;
    }

    public boolean contains(T x) {
        for (int i = 0; i < size; i++) {
            if (items[i].equals(x)) {
                return true;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        ArraySet<String> s = new ArraySet<>();
        // test add function
        s.add("horse");
        System.out.println(s.size);
        s.add("fish");
        System.out.println(s.size);
        // test contains function
        System.out.println(s.contains("horse"));
    }
}

I self create an Arrayset class to store strings with add function and contains function, but the contains function goes wrong. I try to modify my add function but it doesn't works.

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Object.equals(Object)" because "this.items[i]" is null

๐ŸŒ
Syntx Scenarios
syntaxscenarios.com โ€บ home โ€บ java โ€บ how to fix nullpointerexception in java (5 causes & fixes)
How to Fix NullPointerException in Java (5 Causes & Fixes)
March 14, 2026 - So when we call the str.length() it will cause the NullPointerException because the str is pointing to null. ... public class Main { public static void main(String[] args) { String str = getMessage(); System.out.println(str.length()); // This will cause a NullPointerException } public static String getMessage() { return null; } } ... ERROR! Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.length()" because "<local2>" is null at Main.main(Main.java:4)
๐ŸŒ
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.

๐ŸŒ
Sentry
sentry.io โ€บ sentry answers โ€บ java โ€บ what is a nullpointerexception, and how do i fix it?
What is a NullPointerException, and how do I fix it? | Sentry
Of course, in real-world code itโ€™s not normally as simple to identify which variables might be null, as they might be passed in from other methods or classes, or be dependent on user input. You can use some defensive programming techniques to avoid NullPointerExceptions such as always validating user input, and always checking if objects are null before calling their methods.