Mock a Drawable with Mockito and Android - java

How can I mock a Drawable? I have tried this code. It doesn't compile yet:
#Test
public void readStringFromContext_LocalizedString() {
Simulation myObjectUnderTest = new Simulation();
when(mActivity.getResources().getDrawable(R.mipmap.dungeon)).thenReturn(Resources.getSystem()));
when(mWorld.defaultPlace()).thenReturn(new Place("blaha", mActivity.getResources().getDrawable(R.mipmap.dungeon)));
WalkingPerson myObjectUnderTest2 = new WalkingPerson(myObjectUnderTest, mock(AdventureWorld.class), "blaha", 2, mActivity);
String result2 = myObjectUnderTest2.getHelloWorldString();
assertThat(result2, is(FAKE_STRING));
}
I don't know how to mock the drawable. The problem is this statement
when(mActivity.getResources().getDrawable(R.mipmap.dungeon)).thenReturn(Resources.getSystem()));
I also try the following
package dev.game.adventure;
import static junit.framework.Assert.assertEquals;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.CoreMatchers.*;
import static org.mockito.Mockito.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.CoreMatchers.*;
import static org.mockito.Mockito.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import android.content.SharedPreferences;
import java.util.Calendar;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.AssetManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.support.test.InstrumentationRegistry;
import android.util.DisplayMetrics;
#RunWith(MockitoJUnitRunner.class)
public class AdventureTest {
private static final String FAKE_STRING = "HELLO WORLD";
#Mock
Simulation engine;
#Mock
AdventureWorld mWorld;
#Mock
FullscreenActivity mActivity;
#Mock
Drawable mDrawable;
#Test
public void readStringFromContext_LocalizedString() {
Simulation myObjectUnderTest = new Simulation();
when(mActivity.getResources().getDrawable(R.mipmap.dungeon)).thenReturn(mDrawable);
when(mWorld.defaultPlace()).thenReturn(new Place("blaha", mActivity.getResources().getDrawable(R.mipmap.dungeon)));
WalkingPerson myObjectUnderTest2 = new WalkingPerson(myObjectUnderTest, mock(AdventureWorld.class), "blaha", 2, mActivity);
String result2 = myObjectUnderTest2.getHelloWorldString();
assertThat(result2, is(FAKE_STRING));
}
#Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("dev.game.adventure", appContext.getPackageName());
}
}
But I get this error
java.lang.NullPointerException: Attempt to invoke virtual method 'android.graphics.drawable.Drawable android.content.res.Resources.getDrawable(int)' on a null object reference
at dev.game.adventure.AdventureTest.readStringFromContext_LocalizedString(AdventureTest.java:53)
at java.lang.reflect.Method.invoke(Native Method)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37)
at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62)
at org.junit.runners.Suite.runChild(Suite.java:128)
at org.junit.runners.Suite.runChild(Suite.java:27)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
at android.support.test.internal.runner.TestExecutor.execute(TestExecutor.java:58)
at android.support.test.runner.AndroidJUnitRunner.onStart(AndroidJUnitRunner.java:375)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:2074)
Update. It still doesn't work. I'm just wasting my time.
package dev.game.adventure;
import static junit.framework.Assert.assertEquals;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.CoreMatchers.*;
import static org.mockito.Mockito.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.CoreMatchers.*;
import static org.mockito.Mockito.*;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import android.content.SharedPreferences;
import java.util.Calendar;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.AssetManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.support.test.InstrumentationRegistry;
import android.util.DisplayMetrics;
#RunWith(MockitoJUnitRunner.class)
public class AdventureTest {
private static final String FAKE_STRING = "HELLO WORLD";
#Mock
Simulation engine;
#Mock
AdventureWorld mWorld;
#Mock
FullscreenActivity mActivity;
#Mock
Drawable mDrawable;
#Mock
Resources mResources;
#Mock
Place mPlace;
#Test
// #Ignore
public void readStringFromCowntext_LocalizedString() {
Simulation myObjectUnderTest = new Simulation();
when(mResources.getDrawable(R.mipmap.dungeon)).thenReturn(mDrawable);
when(mActivity.getResources()).thenReturn(mResources);
when(mActivity.getResources().getDrawable(R.mipmap.dungeon)).thenReturn(mDrawable);
when(mWorld.defaultPlace()).thenReturn(mPlace);
WalkingPerson myObjectUnderTest2 = new WalkingPerson(myObjectUnderTest, mock(AdventureWorld.class), "blaha", 2, mActivity);
String result2 = myObjectUnderTest2.getHelloWorldString();
assertThat(result2, is(FAKE_STRING));
}
#Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("dev.game.adventure", appContext.getPackageName());
}
}

You mock mActivity but you don't specify what should happen when calling the getResources() method on this mock. Therefore this method returns null and you run into the NPE.
In order to make it work, you need to return a mock object for the getResources() method as well.
Hope this helps.

Related

Reviving an old java repo and getting this error java.lang.reflect.InaccessibleObjectException: Unable to make field private final

I'm trying to revive an older java repo that needs some changes to be made. I am no java pro by far, but alas it must be done.
The repo specifies OpenJDK-14.0.1 and Gradle-6.5 but I have decided to get it running on a newer version of Java and Gradle so that the next poor soul that comes along may have an easier chance of getting setup.
As such I've gone with OpenJDK-19.0.1 and Gradle-7.5.1 and expectedly there have been some issues.
One being the compile configuration having been removed from Gradle-7.5.1 replaced with implementation and the second needing to update the version for Lombok to a higher version so I have gone with 1.18.24
Now the repo builds and 321 of 330 tests pass with 9 failing. This is where I am stuck. All the failing tests are all in the same file and fail because of the same error. Not being a java pro this error doesn't mean much to me.
So my questions is what causes this error in Java and how is it fixed?
The error and a stripped back version of the code with only one of the failing tests is supplied below.
ERROR
java.lang.reflect.InaccessibleObjectException: Unable to make field private final java.util.Map java.util.Collections$UnmodifiableMap.m accessible: module java.base does not "opens java.util" to unnamed module #48cf768c
at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:354)
at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:297)
at java.base/java.lang.reflect.Field.checkCanSetAccessible(Field.java:178)
at java.base/java.lang.reflect.Field.setAccessible(Field.java:172)
at org.junit.contrib.java.lang.system.EnvironmentVariables.getFieldValue(EnvironmentVariables.java:136)
at org.junit.contrib.java.lang.system.EnvironmentVariables.getEditableMapOfVariables(EnvironmentVariables.java:98)
at org.junit.contrib.java.lang.system.EnvironmentVariables.access$000(EnvironmentVariables.java:34)
at org.junit.contrib.java.lang.system.EnvironmentVariables$EnvironmentVariablesStatement.restoreOriginalVariables(EnvironmentVariables.java:82)
at org.junit.contrib.java.lang.system.EnvironmentVariables$EnvironmentVariablesStatement.evaluate(EnvironmentVariables.java:73)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.runTestClass(JUnitTestClassExecutor.java:110)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.execute(JUnitTestClassExecutor.java:58)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.execute(JUnitTestClassExecutor.java:38)
at org.gradle.api.internal.tasks.testing.junit.AbstractJUnitTestClassProcessor.processTestClass(AbstractJUnitTestClassProcessor.java:62)
at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:51)
at jdk.internal.reflect.GeneratedMethodAccessor124.invoke(Unknown Source)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:33)
at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:94)
at jdk.proxy2/jdk.proxy2.$Proxy5.processTestClass(Unknown Source)
at org.gradle.api.internal.tasks.testing.worker.TestWorker$2.run(TestWorker.java:176)
at org.gradle.api.internal.tasks.testing.worker.TestWorker.executeAndMaintainThreadName(TestWorker.java:129)
at org.gradle.api.internal.tasks.testing.worker.TestWorker.execute(TestWorker.java:100)
at org.gradle.api.internal.tasks.testing.worker.TestWorker.execute(TestWorker.java:60)
at org.gradle.process.internal.worker.child.ActionExecutionWorker.execute(ActionExecutionWorker.java:56)
at org.gradle.process.internal.worker.child.SystemApplicationClassLoaderWorker.call(SystemApplicationClassLoaderWorker.java:133)
at org.gradle.process.internal.worker.child.SystemApplicationClassLoaderWorker.call(SystemApplicationClassLoaderWorker.java:71)
at worker.org.gradle.process.internal.worker.GradleWorkerMain.run(GradleWorkerMain.java:69)
at worker.org.gradle.process.internal.worker.GradleWorkerMain.main(GradleWorkerMain.java:74)
CODE
package com.pastoralcare.filter;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.IOException;
import java.util.UUID;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.contrib.java.lang.system.EnvironmentVariables;
import org.junit.runner.RunWith;
import org.mockito.ArgumentMatchers;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.authenticator.AuthenticationTokenAuthenticator;
import com.authenticator.InterServiceTokenAuthenticator;
import com.authorization.CheckStaffPermissions;
import com.dto.PermissionSetCodeDto;
import com.model.AuthToken;
import com.pastoralcare.constant.RestAPIConstants;
import com.pastoralcare.dto.AuthTokenDto;
import com.pastoralcare.dto.PermissionSetCodesDto;
import com.pastoralcare.dto.TokenDto;
#RunWith(SpringRunner.class)
public class TokenFilterTest {
#InjectMocks
TokenFilter tokenFilter;
#Mock
TokenDto tokenDto;
#MockBean
FilterChain filterChain;
#Mock
PermissionSetCodesDto permissionSetCodesDto;
#Mock
AuthTokenDto authTokenDto;
#Mock
InterServiceTokenAuthenticator internalAuth;
#Mock
AuthenticationTokenAuthenticator authnValidator;
#Mock
CheckStaffPermissions checkStaffPermissions;
#Mock
AuthToken authToken;
#Mock
PermissionSetCodeDto permissionSetCodeDto;
MockHttpServletRequest httpServletRequest = new MockHttpServletRequest();
MockHttpServletResponse httpServletResponse = new MockHttpServletResponse();
#Rule
public final EnvironmentVariables environmentVariables = new EnvironmentVariables();
PermissionSetCodesDto permissionSetsDto;
#Before
public void setUp() {
MockitoAnnotations.initMocks(this);
// tokenFilter = new TokenFilter();
tokenFilter.tokenDto = mock(TokenDto.class);
UUID communityId = UUID.randomUUID();
UUID tenantId = UUID.randomUUID();
tokenFilter.tokenDto.setTenantId(tenantId);
tokenFilter.tokenDto.setCommunityId(communityId);
tokenFilter.tokenDto.setFirstName("name");
tokenFilter.tokenDto.setLastName("surname");
tokenFilter.tokenDto.setTimezoneIanaCode("UTC");
ReflectionTestUtils.setField(tokenFilter, "interServiceAuthKey", "8Y419dV49Jw+yeRho5iUIgLErSztNnlWvfmc2vzi8D8=");
ReflectionTestUtils.setField(tokenFilter, "activeProfile", "activeProfile");
RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(httpServletRequest));
}
#Test
public void testDoFilterActuator() throws ServletException, IOException {
httpServletRequest.setRequestURI("/actuator/");
MockHttpServletResponse mockResp = new MockHttpServletResponse();
FilterChain mockFilterChain = Mockito.mock(FilterChain.class);
tokenFilter.doFilter(httpServletRequest, mockResp, mockFilterChain);
assertEquals(200, mockResp.getStatus());
}
}
By massive coincidence I actually ran into the issue myself a few days after commenting, and thus had to solve it.
I had to replace the old Mockito library with the newer 'inline' version. This can be found at https://mvnrepository.com/artifact/org.mockito/mockito-inline
This version no longer attempts to do things that Java 17 doesn't allow anymore while trying to create a Mock object.

Using mockito-inline MockedConstruction to mock FileInputStream throws Could not initialize mocked construction

I'm trying to get rid of PowerMock and replace it with mockito-inline new feature Mocking object construction ,
as I can't refactor the old source code.
One of the test classes I have is mocking FileInputStream,
the class under test FileViewer
import java.awt.Button;
import java.awt.Event;
import java.awt.Font;
import java.awt.TextArea;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class FileViewer extends java.awt.Frame {
private static final long serialVersionUID = 1L;
Button close;
GUIListener fGuiListener;
public FileViewer() {
super();
fGuiListener = new GUIListener();
addWindowListener(fGuiListener);
}
public FileViewer(String filename) throws IOException {
super("FileViewer: " + filename);
fGuiListener = new GUIListener();
addWindowListener(fGuiListener);
File f = new File(filename);
int size = (int) f.length();
int bytes_read = 0;
byte[] data = new byte[size];
try (FileInputStream in = new FileInputStream(f)) {
while (bytes_read < size)
bytes_read += in.read(data, bytes_read, size - bytes_read);
}
TextArea ta = new TextArea(new String(data, 0), 24, 80);
ta.setFont(new Font("Helvetica", Font.PLAIN, 12));
ta.setEditable(false);
this.add("Center", ta);
close = new Button("Close");
this.add("South", close);
this.pack();
this.show();
}
public boolean action(Event e, Object what) {
if (e.target == close) {
this.hide();
this.dispose();
return true;
} else
return false;
}
}
and the original unit test using powermock was
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.FileInputStream;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
#PowerMockIgnore({ "javax.management.*", "javax.security.*" })
#RunWith(PowerMockRunner.class)
#PrepareForTest({ FileViewer.class, FileInputStream.class, java.awt.Frame.class })
public class FileViewerTest {
String dir = System.getProperty("user.dir");
String fileName = "/testFiles/testRead.txt";
FileInputStream mockStream = null;
#Before
public void setup() throws Exception {
mockStream = Mockito.mock(FileInputStream.class);
when(mockStream.read(any(byte[].class), anyInt(), anyInt())).thenReturn(2000);
PowerMockito.whenNew(FileInputStream.class).withAnyArguments().thenReturn(mockStream);
}
#Test
public void testFileViewer_wFilename() throws Exception {
FileViewer spy = Mockito.spy(new FileViewer(dir + fileName));
verify(mockStream, times(1)).close();
spy.dispose();
}
}
I tried to follow the example Mock Java Constructors With Mockito | Configuration and Examples
and creat a new unit test using MockedConstruction as the following
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.File;
import java.io.FileInputStream;
import org.junit.Test;
import org.mockito.MockedConstruction;
import org.mockito.Mockito;
public class FileViewerMockitoTest {
String dir = System.getProperty("user.dir");
String fileName = "/testFiles/testRead.txt";
#Test
public void testFileViewerWithFilename() throws Exception {
try (MockedConstruction<FileInputStream> mocked = Mockito.mockConstruction(FileInputStream.class,
(mock, context) -> {
// further stubbings ...
when(mock.read(any(), any(), any())).thenReturn((int) new File(dir + fileName).length() + 1);
})) {
FileViewer cut = new FileViewer(dir + fileName);
verify(mocked, times(1)).close();
cut.dispose();
}
}
}
But I got the following Exception
org.mockito.exceptions.base.MockitoException: Could not initialize mocked construction
at java.io.FileInputStream.<init>(FileInputStream.java)
at sun.misc.URLClassPath$FileLoader$1.getInputStream(URLClassPath.java:1385)
at sun.misc.Resource.cachedInputStream(Resource.java:77)
at sun.misc.Resource.getByteBuffer(Resource.java:160)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:455)
at java.net.URLClassLoader.access$100(URLClassLoader.java:74)
at java.net.URLClassLoader$1.run(URLClassLoader.java:369)
at java.net.URLClassLoader$1.run(URLClassLoader.java:363)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:362)
at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:355)
at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
at com.cds.nrd.xss.util.FileViewerMockitoTest.testFileViewerWithFilename(FileViewerMockitoTest.java:30)
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(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
at org.junit.vintage.engine.execution.RunnerExecutor.execute(RunnerExecutor.java:43)
at java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:184)
at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
at java.util.Iterator.forEachRemaining(Iterator.java:116)
at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:482)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:472)
at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:151)
at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:174)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:418)
at org.junit.vintage.engine.VintageTestEngine.executeAllChildren(VintageTestEngine.java:82)
at org.junit.vintage.engine.VintageTestEngine.execute(VintageTestEngine.java:73)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:229)
at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$6(DefaultLauncher.java:197)
at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:211)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:191)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:137)
at org.eclipse.jdt.internal.junit5.runner.JUnit5TestReference.run(JUnit5TestReference.java:98)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:40)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:529)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:756)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:452)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210)
Caused by: java.lang.NullPointerException
at com.cds.nrd.xss.util.FileViewerMockitoTest.lambda$0(FileViewerMockitoTest.java:27)
at org.mockito.internal.creation.bytebuddy.InlineByteBuddyMockMaker$InlineConstructionMockControl.lambda$enable$0(InlineByteBuddyMockMaker.java:710)
at org.mockito.internal.creation.bytebuddy.InlineByteBuddyMockMaker.lambda$new$3(InlineByteBuddyMockMaker.java:272)
at org.mockito.internal.creation.bytebuddy.MockMethodAdvice.handleConstruction(MockMethodAdvice.java:176)
at org.mockito.internal.creation.bytebuddy.inject.MockMethodDispatcher.handleConstruction(MockMethodDispatcher.java:53)
... 57 more
Any idea about the reason of the exception or how to make it work, or any alternate approach?
Found the solution:
We can't set any() parameter in the stub of the lambda function in try-with-resource
(in your case, when(mock.read(any(), any(), any())) in FileViewerMockitoTest), which will cause mock.read(any(), any(), any()) to throw an NPE: "could not unbox null" (don't know what it means).
Just simply replace (all of) these arguments to something like any(ArgClass.class), will solve the NPE problem, so do with the Could not initialize mocked construction MockitoException problem.
(How did I find the problem? By extracting the lambda function as a method, we can get the real description of the NPE in the debug environment.)
(I was surprised that there was no information on the internet other than this question.)

Failed to load ApplicationContext Error in Spring Project

I am trying to run a BooResourcesT test class from within IntelliJ Idea and I am getting the "Failed to load ApplicationContext" exception.
Please look at my code::
package lms.co;
import static org.hamcrest.CoreMatchers.hasItems;
import static org.hamcrest.Matchers.is;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationContextLoader;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import com.fasterxml.jackson.databind.ObjectMapper;
import lms.co.controller.BooksResourceImpl;
import lms.co.model.Book;
import lms.co.repository.BookRepository;
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = LMSApplication.class, loader = SpringApplicationContextLoader.class)
#WebAppConfiguration
public class BooksResourceITTest {
private MockMvc mockMvc;
#Autowired
private BookRepository booksRepo;
#Autowired
private ObjectMapper mapper;
private BooksResourceImpl booksResource;
#Before
public void setup(){
MockitoAnnotations.initMocks(this);
booksResource = new BooksResourceImpl();
mockMvc = MockMvcBuilders.standaloneSetup(booksResource).build();
ReflectionTestUtils.setField(booksResource, "booksRepo", booksRepo);
}
#Test
public void addBookTest() throws Exception{
Book book = new Book("isbn1","Test1","Test Author","","","","","");
String body = mapper.writeValueAsString(book);
mockMvc.perform(post("/api/book")
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON)
.content(body))
.andExpect(status().isCreated());
}
#Test
public void getBookByIsbnTest() throws Exception {
Book book = new Book("isbn2","Test2","Test Author","","","","","");
booksRepo.addBook(book);
MvcResult result = mockMvc.perform(get("/api/book/isbn2")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$.title",is("Test2")))
.andReturn();
}
#Test
public void getBooksTest() throws Exception {
Book book1 = new Book("isbn3","Test3","Test Author","","","","","");
booksRepo.addBook(book1);
Book book2 = new Book("isbn4","Test4","Test Author","","","","","");
booksRepo.addBook(book2);
MvcResult result = mockMvc.perform(get("/api/books")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$[*].title", hasItems("Test4", "Test3")))
.andReturn();
}
}
Error is
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:94)
at org.springframework.test.context.DefaultTestContext.getApplicationContext(DefaultTestContext.java:72)
at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:170)
at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:110)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:212)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:200)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:259)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:261)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:219)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:83)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:68)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor': Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: javax/xml/bind/ValidationException
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1574)
... 24 more
Caused by: java.lang.NoClassDefFoundError: javax/xml/bind/ValidationException
at java.base/java.lang.ClassLoader.defineClass1(Native Method)
at java.base/java.lang.ClassLoader.defineClass(ClassLoader.java:1017)
at java.base/java.security.SecureClassLoader.defineClass(SecureClassLoader.java:174)
at java.base/jdk.internal.loader.BuiltinClassLoader.defineClass(BuiltinClassLoader.java:800)
at java.base/jdk.internal.loader.BuiltinClassLoader.findClassOnClassPathOrNull(BuiltinClassLoader.java:698)
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClassOrNull(BuiltinClassLoader.java:621)
... 56 more
I am new in spring project and this is my 1st time of getting this type error so please help me and please don't close my question if their is an para mistakes.Please...

How to solve internal error from server (test)?

guys. I'm testing method and in test it's name is testGetAuthorizedUserPublicInfo. This method have to return an User object. (So i created getUser method which return our new user).
Then after calling some methods on mockMvc objects try to perform get method (url is the same like in Controller class).
But i getting 500 response (instead of 200).
Can anyone say where is my mistake?? it would be really great )
`
package com.softserve.academy.spaced.repetition.controller;
import com.softserve.academy.spaced.repetition.controller.handler.ExceptionHandlerController;
import com.softserve.academy.spaced.repetition.domain.Account;
import com.softserve.academy.spaced.repetition.domain.Person;
import com.softserve.academy.spaced.repetition.domain.User;
import com.softserve.academy.spaced.repetition.domain.enums.AccountStatus;
import com.softserve.academy.spaced.repetition.domain.enums.AuthenticationType;
import com.softserve.academy.spaced.repetition.domain.enums.ImageType;
import com.softserve.academy.spaced.repetition.domain.enums.LearningRegime;
import com.softserve.academy.spaced.repetition.service.UserService;
import org.hamcrest.Matchers;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.context.MessageSource;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import java.util.Date;
import java.util.Locale;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
#RunWith(MockitoJUnitRunner.class)
public class UserControllerTest {
private MockMvc mockMvc;
private static final long USER_ID = 1L;
#InjectMocks
UserController userController;
#Mock
UserService userService;
#Before
public void setUp() {
mockMvc = MockMvcBuilders.standaloneSetup(userController)
.setControllerAdvice(new ExceptionHandlerController())
.build();
}
#Test
public void testGetAuthorizedUserPublicInfo() throws Exception {
when(userService.getAuthorizedUser()).thenReturn(getUser());
mockMvc.perform(get("/api/user/details")
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(status().isOk())
.andExpect(jsonPath("$.id", Matchers.is(1)));
}
private User getUser() {
Account account;
Person person;
User user;
account = new Account();
account.setId(USER_ID);
account.setPassword("12345678");
account.setEmail("a#a.a");
account.setAuthenticationType(AuthenticationType.LOCAL);
account.setStatus(AccountStatus.ACTIVE);
account.setDeactivated(false);
account.setLastPasswordResetDate(new Date());
account.setLearningRegime(LearningRegime.BAD_NORMAL_GOOD_STATUS_DEPENDING);
account.setCardsNumber(1);
person = new Person();
person.setId(USER_ID);
person.setFirstName("firstname");
person.setLastName("lastname");
person.setImageType(ImageType.NONE);
user = new User();
user.setId(USER_ID);
user.setAccount(account);
user.setPerson(person);
return user;
}
}
`
here is what i've got after executing this test method
`
java.lang.AssertionError: Status
Expected :200
Actual :500
<Click to see difference>
at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:54)
at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:81)
at org.springframework.test.web.servlet.result.StatusResultMatchers$10.match(StatusResultMatchers.java:664)
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:171)
at com.softserve.academy.spaced.repetition.controller.UserControllerTest.testGetAuthorizedUserPublicInfo(UserControllerTest.java:71)
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(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37)
at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Process finished with exit code 255
`

java.io.FileNotFoundException: Could not open ServletContext resource [/application.properties]

org.springframework.beans.factory.BeanDefinitionStoreException: Failed to parse configuration class [com.gaian.adwize.ssp.main.SSPStarter]; nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/application.properties] at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:187) at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:324) at
Test class
----------
package com.gaian.adwize.swagger;
import com.gaian.adwize.ssp.main.SSPStarter;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import java.io.BufferedWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import org.springframework.context.annotation.ImportResource;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessResponse;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.prettyPrint;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
#WebAppConfiguration
#RunWith(SpringJUnit4ClassRunner.class)
#AutoConfigureRestDocs(outputDir = "build/asciidoc/snippets")
#SpringBootTest(classes = {SSPStarter.class, SwaggerConfig.class})
#AutoConfigureMockMvc
public class Swagger2MarkupTest {
private static final Logger LOG = LoggerFactory.getLogger(Swagger2MarkupTest.class);
#Autowired
private MockMvc mockMvc;
#Test
public void createSpringfoxSwaggerJson() throws Exception {
//String designFirstSwaggerLocation = Swagger2MarkupTest.class.getResource("/swagger.yaml").getPath();
String outputDir = System.getProperty("io.springfox.staticdocs.outputDir");
MvcResult mvcResult = this.mockMvc.perform(get("/v2/api-docs")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andReturn();
MockHttpServletResponse response = mvcResult.getResponse();
String swaggerJson = response.getContentAsString();
Files.createDirectories(Paths.get(outputDir));
try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(outputDir, "swagger.json"), StandardCharsets.UTF_8)){
writer.write(swaggerJson);
}
}
}
Failed to load Application Context and could not be able to load properties file which is in classpath
Anyone please help me??

Categories