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 ;)
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 ;)
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.
java - What is a NullPointerException, and how do I fix it? - Stack Overflow
java - Getting NullPointerException in JUNit testing - Stack Overflow
Getting nullpointer exception when updated to junit5 in serenity bdd tests
spring boot - JUnit - java.lang.NullPointerException: Cannot invoke "..." because "this.modelMapper" is null - Stack Overflow
There are two overarching types of variables in Java:
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
intorcharare primitives.References: variables that contain the memory address of an
Objecti.e. variables that refer to anObject. If you want to manipulate theObjectthat 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 typeObjectare 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
NullPointerExceptionif one of its operands is a boxed null reference - An unboxing conversion throws a
NullPointerExceptionif the boxed value is null. - Calling
superon a null reference throws aNullPointerException. 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 aNullPointerExceptionwhenfoois null.foo.new SomeInnerClass()throws aNullPointerExceptionwhenfoois null.Method references of the form
name1::name2orprimaryExpression::namethrows aNullPointerExceptionwhen evaluated whenname1orprimaryExpressionevaluates to null.a note from the JLS here says that,
someInstance.someStaticMethod()doesn't throw an NPE, becausesomeStaticMethodis static, butsomeInstance::someStaticMethodstill throw an NPE!
* Note that the JLS probably also says a lot about NPEs indirectly.
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.)
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 ) { ...
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);
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)
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
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.