Need help resolving error:
kotlin.UninitializedPropertyAccessException: lateinit property ultraService has not been initialized
at com.example.ultrasonic.service.UltraServiceTest.get all Ultra(UltraServiceTest.kt:39)
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.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)
service class:
https://github.com/swapab/ultrasonic/blob/master/src/main/kotlin/com/example/ultrasonic/service/UltraService.kt
package com.example.ultrasonic.service
import com.example.ultrasonic.domain.Ultra
import com.example.ultrasonic.repository.UltraRepository
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
#Service
class UltraService {
#Autowired
private lateinit var UltraRepository: UltraRepository
fun publish(Ultra: Ultra): Ultra =
UltraRepository.save(Ultra)
fun all(): List<Ultra> =
UltraRepository.findAll()
}
service class test:
https://github.com/swapab/ultrasonic/blob/master/src/test/kotlin/com/example/ultrasonic/service/UltraServiceTest.kt
package com.example.ultrasonic.service
import com.example.ultrasonic.domain.Ultra
import com.example.ultrasonic.repository.UltraRepository
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import org.junit.Before
import org.junit.Test
import org.mockito.Mock
import org.mockito.Mockito
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.test.context.ContextConfiguration
import java.time.LocalDate
#ContextConfiguration(classes = [UltraService::class])
class UltraServiceTest {
#Autowired
lateinit var ultraService: UltraService
#Mock
lateinit var UltraRepository: UltraRepository
lateinit var sampleUltra: Ultra
lateinit var sampleUltraJsonString: String
private val mapper = jacksonObjectMapper()
#Before
fun setUp() {
sampleUltra = Ultra(1,
"latest sample Ultra")
sampleUltraJsonString = mapper.writeValueAsString(sampleUltra)
}
#Test
fun `get all Ultra`() {
Mockito.doReturn(listOf(sampleUltra)).`when`(ultraService).all()
ultraService.all()
Mockito.verify(UltraRepository).findAll()
}
}
The reproducer is here: https://github.com/swapab/ultrasonic
Have you tried annotating your test class to use the SpringRunner unit test harness?
#RunWith(SpringRunner.class)
class UltraServiceTest {
}
See http://www.baeldung.com/spring-boot-testing
Related
I'm trying to run an Appium test with selenium, PageFactory.initElements
this Code works only on JDK Amazon corretto-1.8
getting an error on all higher JDKs. (11,15,19)
My actual Goal is to upgrade my Java project level to JDK 11 or higher.
java.lang.RuntimeException: java.lang.NoSuchMethodException: jdk.proxy2.$Proxy8.proxyClassLookup()
at io.appium.java_client.pagefactory.bys.builder.AppiumByBuilder.prepareAnnotationMethods(AppiumByBuilder.java:84)
at io.appium.java_client.pagefactory.bys.builder.AppiumByBuilder.getFilledValue(AppiumByBuilder.java:91)
at io.appium.java_client.pagefactory.bys.builder.AppiumByBuilder.createBy(AppiumByBuilder.java:147)
at io.appium.java_client.pagefactory.DefaultElementByBuilder.getBys(DefaultElementByBuilder.java:133)
at io.appium.java_client.pagefactory.DefaultElementByBuilder.buildMobileNativeBy(DefaultElementByBuilder.java:175)
at io.appium.java_client.pagefactory.DefaultElementByBuilder.buildBy(DefaultElementByBuilder.java:204)
at io.appium.java_client.pagefactory.AppiumElementLocatorFactory.createLocator(AppiumElementLocatorFactory.java:66)
at io.appium.java_client.pagefactory.AppiumElementLocatorFactory.createLocator(AppiumElementLocatorFactory.java:53)
at io.appium.java_client.pagefactory.AppiumElementLocatorFactory.createLocator(AppiumElementLocatorFactory.java:1)
at org.openqa.selenium.support.pagefactory.DefaultFieldDecorator.decorate(DefaultFieldDecorator.java:56)
at io.appium.java_client.pagefactory.AppiumFieldDecorator.decorate(AppiumFieldDecorator.java:154)
at org.openqa.selenium.support.PageFactory.proxyFields(PageFactory.java:113)
at org.openqa.selenium.support.PageFactory.initElements(PageFactory.java:105)
at stable.NewTest.setUp(NewTest.java:24)
at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104)
at java.base/java.lang.reflect.Method.invoke(Method.java:578)
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.RunBefores.evaluate(RunBefores.java:24)
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 com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
at com.intellij.rt.junit.IdeaTestRunner$Repeater$1.execute(IdeaTestRunner.java:38)
at com.intellij.rt.execution.junit.TestsRepeater.repeat(TestsRepeater.java:11)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:35)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:235)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)
Caused by: java.lang.NoSuchMethodException: jdk.proxy2.$Proxy8.proxyClassLookup()
at java.base/java.lang.Class.getMethod(Class.java:2277)
at io.appium.java_client.pagefactory.bys.builder.AppiumByBuilder.prepareAnnotationMethods(AppiumByBuilder.java:82)
... 35 more
Here is My Code
package stable;
import io.appium.java_client.AppiumDriver;
import io.appium.java_client.MobileElement;
import io.appium.java_client.pagefactory.AndroidFindBy;
import io.appium.java_client.pagefactory.AppiumFieldDecorator;
import io.appium.java_client.pagefactory.iOSXCUITFindBy;
import model.util.AppiumDriverBuilder;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.support.PageFactory;
public class NewTest {
private AppiumDriver driver;
public Po page;
#Before
public void setUp() throws Exception {
driver = new AppiumDriverBuilder().build(false, "testName.getMethodName()");
page = new Po();
PageFactory.initElements(new AppiumFieldDecorator(driver), page);
}
#Test
public void first() {
page.skip_button.click();
}
class Po {
#iOSXCUITFindBy(accessibility = "Skip")
#AndroidFindBy(id = "onboarding_skip_button")
public MobileElement skip_button;
}
}
Fails here: PageFactory.initElements(new AppiumFieldDecorator(driver), page);
I'm using
Appium java client 7.4
maven-surefire-plugin 3.0.05M
Junit 5.4.2
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);
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.
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
`
here is my junit which i am trying to implement.
import static org.mockito.Mockito.when;
import java.util.HashMap;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.runners.MockitoJUnitRunner;
#RunWith(MockitoJUnitRunner.class)
public class Power_Test {
#InjectMocks
ReportUtil w_res = new ReportUtil();
CollectionUtil mock = org.mockito.Mockito.mock(CollectionUtil.class);
#Test
public void test_removeHashedSettings() throws Exception {
HashMap<String, String> w_abc = new HashMap<String, String>();
w_abc.put("abc", "89");
when(mock.createHashMap("abc:89",":")).thenReturn(w_abc);
Assert.assertEquals(ReportUtil.removeHashedSettings("1", "abc:89", ":"),"abc:89:",0);
}
}
I want to mock createHashMap() method which is static method.
Below is an error trace which i am getting while running the above junit.
org.mockito.exceptions.misusing.MissingMethodInvocationException:
when() requires an argument which has to be 'a method call on a mock'.
For example:
when(mock.getArticles()).thenReturn(articles);
Also, this error might show up because:
1. you stub either of: final/private/equals()/hashCode() methods.
Those methods cannot be stubbed/verified.
Mocking methods declared on non-public parent classes is not supported.
2. inside when() you don't call method on mock but on some other object.
at com.de.base.util.general.Power_Test.test_removeHashedSettings(Power_Test.java:34)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at Sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
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.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)
please help.
here is createHashMap Api
public static HashMap<String, String> createHashMap(String a_NameValStr, String a_Delim)
{
HashMap<String, String> w_KeyVal = new HashMap<String, String>();
if (LOGGER.isInfoEnabled()) LOGGER.info("CollectionUtil:createHashMap:Hashing string: "+ a_NameValStr );
if(a_NameValStr == null) return w_KeyVal;
StringTokenizer w_StrTkn = new StringTokenizer(a_NameValStr, a_Delim);
if( w_StrTkn.countTokens() == 0 || (w_StrTkn.countTokens()%2) != 0 )
{
LOGGER.warn("CollectionUtil:createHashMap:Invalid number of tokens to hash: "+ a_NameValStr+":"+w_StrTkn.countTokens() );
return w_KeyVal;
}
while (w_StrTkn.hasMoreTokens()) w_KeyVal.put( w_StrTkn.nextToken(), w_StrTkn.nextToken());
return w_KeyVal;
}