I am trying to access main class variable from my test class using java reflection api but i am getting exception like below can some one guide me please
Main class
package com.example.microservice.controller;
public class PrivateStatic {
public void process() {
String message = "data";
if (message != null && message.equalsIgnoreCase("data")) {
System.out.println("print message"+message);
} else {
System.out.println("empty message"+message);
}
}
}
Test class
package com.example.microservice.controller;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Spy;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@SpringBootTest
@RunWith(SpringJUnit4ClassRunner.class)
public class PrivateStaticTest {
@InjectMocks
PrivateStatic private_Static;
@Test
public void processTest() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
final java.lang.reflect.Field field = private_Static.getClass().getDeclaredField("message");
final boolean origionalValue = field.isAccessible();
field.setAccessible(true);
field.set(private_Static, "data");
field.setAccessible(origionalValue);
}
}
Exception
java.lang.NullPointerException
at com.example.microservice.controller.PrivateStaticTest.processTest(PrivateStaticTest.java:22)
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.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:675)
at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
Aucun commentaire:
Enregistrer un commentaire