How to solve internal error from server (test)? - java

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
`

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.

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 get rid of NullPointerException in Mockito unit test

I want to unit test rentBook method that is rensposible for renting.
Here is the #Service
package bookrental.service.book.rentals;
import bookrental.model.account.User;
import bookrental.model.book.Book;
import bookrental.model.book.BookRentals;
import bookrental.repository.account.UserRepository;
import bookrental.repository.book.BookRepository;
import bookrental.repository.book.BookRentalsRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
#Service
public class BookRentalService {
private final UserRepository userRepository;
private final BookRepository bookRepository;
private final BookRentalsRepository bookRentalsRepository;
#Autowired
public BookRentalService(BookRepository bookRepository, BookRentalsRepository bookRentalsRepository, UserRepository userRepository) {
this.bookRepository = bookRepository;
this.bookRentalsRepository = bookRentalsRepository;
this.userRepository = userRepository;
}
public String rentBook(int userID, int bookID) {
if (userRepository.doesAccountExistsWithGivenID(userID)) {
if (bookRepository.doesBookExistsWithGivenID(bookID)) {
Book bookToRent = bookRepository.findOne(bookID);
if (bookToRent.isAvailable()) {
updateBookAvailabilityAndSaveToDb(bookToRent);
BookRentals preparedBookToRent = prepareBookToRent(userID, bookID);
bookRentalsRepository.save(preparedBookToRent);
} else {
throw new IllegalArgumentException("Book is not available");
}
} else {
throw new IllegalArgumentException("Book does not exist!");
}
} else {
throw new IllegalArgumentException("Account does not exist!");
}
return "Book was rented";
}
private BookRentals prepareBookToRent(int userID, int bookID) {
return new BookRentals(new Book(bookID), new User(userID));
}
private void updateBookAvailabilityAndSaveToDb(Book bookToRent) {
bookToRent.setAvailable(false);
bookRepository.save(bookToRent);
}
public List<BookRentals> findAllRentals() {
List<BookRentals> rentedBooks = new ArrayList<>();
bookRentalsRepository.findAll().forEach(rentedBooks::add);
return rentedBooks;
}
}
I tried to unit test it, but getting NPE. I do not know what I am doing wrong.
package bookrental.service.book.rentals;
import bookrental.model.account.User;
import bookrental.model.book.Book;
import bookrental.model.book.BookRentals;
import bookrental.repository.book.BookRentalsRepository;
import bookrental.repository.book.BookRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import static org.junit.Assert.*;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
#RunWith(MockitoJUnitRunner.class)
public class BookRentalServiceTest {
#Mock
BookRentalsRepository bookRentalsRepository;
#Mock
BookRepository bookRepository;
#InjectMocks
BookRentalService bookRentalService;
#Test
public void rentBook() {
Book book = createDummyBook();
User user = createDummyUser();
BookRentals bookToRent = createDummyRentedBook(user, book);
when(bookRentalsRepository.save(bookToRent)).thenReturn(bookToRent);
bookRentalService.rentBook(user.getId(), book.getId());
verify(bookRentalsRepository).save(bookToRent);
verify(bookRentalService, times(1)).rentBook(user.getId(), book.getId());
}
#Test
public void findAllRentals() {
}
private Book createDummyBook() {
return new Book(0, "W pustyni i w puszczy", "Henryk Sienkiewicz", "dramat", true);
}
private BookRentals createDummyRentedBook(User user, Book book) {
return new BookRentals(book, user);
}
private User createDummyUser() {
return new User(0, "must", "123");
}
}
Stacktrace:
java.lang.NullPointerException
at bookrental.service.book.rentals.BookRentalService.rentBook(BookRentalService.java:30)
at bookrental.service.book.rentals.BookRentalServiceTest.rentBook(BookRentalServiceTest.java:38)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:564)
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.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)
///
EDIT
#Test
public void rentBook() {
Book book = createDummyBook();
User user = createDummyUser();
BookRentals bookToRent = createDummyRentedBook(user, book);
when(userRepository.doesAccountExistsWithGivenID(user.getId())).thenReturn(true);
when(bookRepository.doesBookExistsWithGivenID(book.getId())).thenReturn(true);
when(bookRepository.findOne(book.getId())).thenReturn(book);
when(userRepository.findOne(user.getId())).thenReturn(user);
String expected = "Book was rented";
assertEquals(expected, bookRentalService.rentBook(user.getId(), book.getId()));
verify(bookRentalsRepository, times(1)).save(bookToRent);
}
STACKTRACE:
Argument(s) are different! Wanted:
bookRentalsRepository.save(
bookrental.model.book.BookRentals#7574b32f
);
-> at bookrental.service.book.rentals.BookRentalServiceTest.rentBook(BookRentalServiceTest.java:48)
Actual invocation has different arguments:
bookRentalsRepository.save(
bookrental.model.book.BookRentals#1c62c511
);
-> at bookrental.service.book.rentals.BookRentalService.rentBook(BookRentalService.java:36)
Comparison Failure: <Click to see difference>
Argument(s) are different! Wanted:
bookRentalsRepository.save(
bookrental.model.book.BookRentals#7574b32f
);
-> at bookrental.service.book.rentals.BookRentalServiceTest.rentBook(BookRentalServiceTest.java:48)
Actual invocation has different arguments:
bookRentalsRepository.save(
bookrental.model.book.BookRentals#1c62c511
);
-> at bookrental.service.book.rentals.BookRentalService.rentBook(BookRentalService.java:36)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:488)
at bookrental.service.book.rentals.BookRentalServiceTest.rentBook(BookRentalServiceTest.java:48)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:564)
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.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)
From the stack trace, it seems it fails because you didn't mock also the user repository.
Add the following:
#Mock
UserRepository userRepository;
...
when(userRepository.doesAccountExistsWithGivenID(user.getId()).thenReturn(true);

Junit for RestController - Assertion Error

I have created an rest api and tested via postman and able to get success response as expected. Now i have created Junit test case for the above api but while executing getting "java.lang.AssertionError: Status expected:<200> but was:<415> ". Not able to figure out why this exception is happening.
I'm new to both Mockito and MockMVC so any help would be appreciated.
Below is my test class
package com.example.demo.hystricks;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.io.Serializable;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import org.apache.commons.lang.SerializationUtils;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.MockitoAnnotations;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.RequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import com.example.demo.DemoController;
import com.example.demo.DemoService;
import com.example.demo.InputModel;
#RunWith(SpringJUnit4ClassRunner.class)
#SpringBootTest(classes = DemoController.class)
public class DemoControllerTest {
private MockMvc mockMvc;
#InjectMocks
private DemoController demoController;
#MockBean
private DemoService demoService;
#MockBean
private MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter;
#Before
public void setUp() {
MockitoAnnotations.initMocks(this);
DemoController demoController = new DemoController(demoService);
this.mockMvc = MockMvcBuilders
.standaloneSetup(demoController).
setMessageConverters(mappingJackson2HttpMessageConverter).build();
}
#Test
public void postData() throws Exception {
InputModel inputModel = new InputModel("12345","Test","CSC",getEventTime());
System.out.println("before api....");
RequestBuilder requestBuilder = MockMvcRequestBuilders.post("/demoService")
.accept(MediaType.APPLICATION_JSON)
.content(inputModel.toString())
.contentType(MediaType.APPLICATION_JSON);
mockMvc.perform(requestBuilder)
.andDo(MockMvcResultHandlers.print())
.andExpect(status().isOk());
System.out.println("after api....");
}
private LocalDateTime getEventTime() {
Instant instant = Instant.ofEpochMilli(Instant.now().toEpochMilli());
LocalDateTime eventTimestamp = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
return eventTimestamp;
}
}
My Rest Controller
#RestController
public class DemoController {
private static final Logger LOGGER = LoggerFactory.getLogger(DemoController.class);
public final DemoService demoService;
public DemoController(DemoService demoService) {
this.demoService = demoService;
}
#RequestMapping(value = "demoService",method = RequestMethod.POST)
public ResponseEntity<String> postData(
#RequestBody InputModel inputModel){
LOGGER.info("DemoService Entered successfully");
demoService.postData(inputModel.getId(),inputModel.getName(),
inputModel.getDepartment(), inputModel.getJoinDate());
LOGGER.info("DemoService Exited successfully");
return new ResponseEntity<String>("success",HttpStatus.OK) ;
}
}
Console Message before api:
>2018-10-16 12:15:49.391 WARN 6200 --- [ main] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/json' not supported]
2018-10-16 12:15:49.437 INFO 6200 --- [ Thread-3] o.s.w.c.s.GenericWebApplicationContext : Closing org.springframework.web.context.support.GenericWebApplicationContext#5023bb8b: startup date [Tue Oct 16 12:15:48 IST 2018]; parent: org.springframework.context.annotation.AnnotationConfigApplicationContext#76a4ebf2
Failure Stack Trace:
>java.lang.AssertionError: Status expected:<200> but was:<415>
at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:55)
at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:82)
at org.springframework.test.web.servlet.result.StatusResultMatchers.lambda$matcher$9(StatusResultMatchers.java:619)
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:178)
at com.example.demo.hystricks.DemoControllerTest.postData(DemoControllerTest.java:68)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
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.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:73)
at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:83)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
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$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:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
The issue is on this line:
#MockBean
private MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter;
You are mocking this converter. Create a instance using new instead:
this.mockMvc = MockMvcBuilders
.standaloneSetup(controller).
setMessageConverters(new MappingJackson2HttpMessageConverter()).build();
Or as rightly mentioned by M. Dienum, you can do away with the below 2 lines from setUp() method and it'll work:
DemoController demoController = new DemoController(demoService);
this.mockMvc = MockMvcBuilders
.standaloneSetup(demoController).
setMessageConverters(mappingJackson2HttpMessageConverter).build();
After doing all this if you run into 400 error then your toString() method isn't producing valid json.

Mock a Drawable with Mockito and Android

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.

Categories