NullPointerException in the BeforeClass (spring boot) - spring-boot

I want to make an insert in my DB before all tests just once. That's what I'm trying to do in the setUp() method. But got nullpointer. Spring boot version is 1.5.1.RELEASE. Any ideas?
This is from my test class:
#Autowired
private static UserRepository userRepository;
#BeforeClass
public static void setUp() {
User user = User.
.builder()
.id(10)
.name("John")
.build();
userRepository.deleteAll(); //NullPointerException at this step
userRepository.save(user);
}
This is my entity class:
#Entity
#Table(schema="test", name = "TBL_USERS")
#AllArgsConstructor
#Builder
#Data public class User implements Persistable<String>{
#Id
#Column(name = "ID", columnDefinition = "decimal")
private String id;
#Column(name = "NAME", columnDefinition = "char", nullable = false)
private String name;
...
}
This is the interface:
public interface UserRepository extends JpaRepository<User, String> {}
The stack trace:
java.lang.NullPointerException
at com.company.myapp.get.GetUserTest.setUp(GetUserTest.java:58)
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:497)
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.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:191)
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:51)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:237)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
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:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)

Short answer: You can not inject static UserRepository (#Autowired)
Please read here Reason we could not inject static field

It doesn't look like you initialized userRepository to anything in your beforeClass method before calling deleteAll() on it. That's why you got your NPE.

Is your test class annotated with #RunWith(SpringRunner.class)?

You need to do something like this..
#RunWith(SpringRunner.class)
#SpringBootTest
public class XXXTest {
#Autowired
private UserRepository userRepository;
#Before
public void setUp() {
......
}

Related

MockMvc peform is return nullPointerException in integration tests

I'm trying to run integration tests for my Spring project, it's a simple get method that returns a String output from the DB for the id given. But I keep getting a NullPointerException on the Mockmvc in the MockMvc.perform within my tests.
Here is the test:
#WebMvcTest(OutputController.class)
public class OutputControllerTests {
#Autowired
private MockMvc mockMvc;
#MockBea
OutputService outputService;
#Test
public void returnOutputForValidId() throws Exception {
OutputService service = Mockito.mock(OutputService.class);
when(service.findOutputById("TEST")).thenReturn("Test output");
String getOutputMapping = "/output/{systemID}";
String id = "TEST";
mockMvc.perform(get(getOuputMapping, id))
.andDo(print()).andExpect(status().isOk())
.andExpect(content().string("Test output"));
}
Here is the controller - OutputController:
#RestController
public class OutputController {
private final OutputService outputService;
public OutputController(OutputService outputService) {
this.outputService = outputService;
}
#GetMapping("/output/{id}")
#CrossOrigin
public String getOutputByID(#PathVariable String Id) {
String output = outputService.findOutputById(Id);
return output;
}
}
The full error is :
java.lang.NullPointerException
at .com.output.OutputControllerTests.returnOutputForValidId(OutputControllerTests.java:37)
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:59)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)
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.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)
You don't need to autowire MockMvc object. Try with this instead:
import org.junit.jupiter.api.BeforeEach;
//...
private MockMvc mockMvc;
//...
#BeforeEach
public void setUp(WebApplicationContext context) {
mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
}

Null after #InjectMocks in Mockito Junit

I am having some troubles passing a dependancy while unit testing with JUnit.
Consider these pieces of code:
This is the dependacy injecton into the class which i want to test, lets call it Service.
error log trace
java.lang.NullPointerException
at com.example.demo.service.ServiceClass.getCustomerById(ServiceClass.java:50)
at com.example.demo.service.ServiceClassTest.getCustomerByIdTest(ServiceClassTest.java:46)
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.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
ServiceClass
#Service
public class ServiceClass {
public static final String CRM_JPA_URI = "http://localhost:9000/api/tickets/";
#Autowired
RestTemplate restTemplate;
public Customer getCustomerById(int customerId) {
ResponseEntity<Customer> entity = restTemplate.getForEntity(CRM_JPA_URI +"ticket/{customerId}",
Customer.class, customerId);
return entity.getBody();
}
}
ServiceClassTest
#RunWith(MockitoJUnitRunner.class)
public class ServiceClassTest {
#Mock
RestTemplate mockRestTemplate;
#InjectMocks
ServiceClass serviceClass;
/**
* getCustomerByIdTest
*/
#Test
public void getCustomerByIdTest(){
Customer customer = new Customer();
customer.setPassengerName("Ramesh");
customer.setBookingDate("09/09/2019");
customer.setDestStation("pamur");
customer.setEmail("r#gmail.com");
customer.setSourceStation("ongole");
Mockito.lenient().when(mockRestTemplate.getForEntity("http://localhost:9000/api/tickets/ticket/1", Customer.class)).
thenReturn(new ResponseEntity<Customer>(customer,HttpStatus.OK));
System.out.println("object is--->"+serviceClass.getCustomerById(1));
assertEquals(customer, serviceClass.getCustomerById(1));
}
}
Try calling
MockitoAnnotations.initMocks(this);
in your test method or #Before setup() method

Acceptance Test with MockMultipartFile, and HttpMessageConversionException occurs

I tried AcceptanceTest with MockMultipartFile class in springboot and HttpMessageConversionException occurs.
and I saw many code work with File Object but as you see my dto contains MultipartFile..
could you know me why It doesn't works? and How to fix it?
It is jackson converting error, so I check all of get~ method and
I tried for making CustomMultipartFile and override getInputStream method and attach #JsonIgnore
but it make another error and doesn't work
org.springframework.http.converter.HttpMessageConversionException: Type definition error: [simple type, class java.io.ByteArrayInputStream]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class java.io.ByteArrayInputStream and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: org.springframework.mock.web.MockMultipartFile["inputStream"])
at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.writeInternal(AbstractJackson2HttpMessageConverter.java:293)
at org.springframework.http.converter.AbstractGenericHttpMessageConverter.writeInternal(AbstractGenericHttpMessageConverter.java:112)
at org.springframework.http.converter.AbstractHttpMessageConverter.write(AbstractHttpMessageConverter.java:227)
at org.springframework.http.converter.FormHttpMessageConverter.writePart(FormHttpMessageConverter.java:417)
at org.springframework.http.converter.FormHttpMessageConverter.writeParts(FormHttpMessageConverter.java:393)
at org.springframework.http.converter.FormHttpMessageConverter.writeMultipart(FormHttpMessageConverter.java:373)
at org.springframework.http.converter.FormHttpMessageConverter.write(FormHttpMessageConverter.java:277)
at org.springframework.http.converter.FormHttpMessageConverter.write(FormHttpMessageConverter.java:95)
at org.springframework.web.client.RestTemplate$HttpEntityRequestCallback.doWithRequest(RestTemplate.java:948)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:733)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:670)
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:579)
at org.springframework.boot.test.web.client.TestRestTemplate.exchange(TestRestTemplate.java:774)
at com.mappractice.demo.acceptanceTest.AcceptanceTest.sendFile(AcceptanceTest.java:51)
at com.mappractice.demo.acceptanceTest.ImageAcceptanceTest.이미지_생성_API_성공(ImageAcceptanceTest.java:46)
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.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:84)
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.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
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.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)
Caused by: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class java.io.ByteArrayInputStream and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: org.springframework.mock.web.MockMultipartFile["inputStream"])
at com.fasterxml.jackson.databind.exc.InvalidDefinitionException.from(InvalidDefinitionException.java:77)
at com.fasterxml.jackson.databind.SerializerProvider.reportBadDefinition(SerializerProvider.java:1191)
at com.fasterxml.jackson.databind.DatabindContext.reportBadDefinition(DatabindContext.java:313)
at com.fasterxml.jackson.databind.ser.impl.UnknownSerializer.failForEmpty(UnknownSerializer.java:71)
at com.fasterxml.jackson.databind.ser.impl.UnknownSerializer.serialize(UnknownSerializer.java:33)
at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:727)
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:719)
at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:155)
at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider._serialize(DefaultSerializerProvider.java:480)
at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:319)
at com.fasterxml.jackson.databind.ObjectWriter$Prefetch.serialize(ObjectWriter.java:1396)
at com.fasterxml.jackson.databind.ObjectWriter.writeValue(ObjectWriter.java:913)
at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.writeInternal(AbstractJackson2HttpMessageConverter.java:287)
... 45 more
TEST CODE
public class ImageAcceptanceTest extends AcceptanceTest {
private static final String API_IMAGE_URI = "/api/image";
private static MockMultipartFile content;
private static Image image;
private static PositionedImageDTO positionedImageDTO;
#BeforeClass
public static void init() {
content = new MockMultipartFile("file",
"ded.png",
"image/png",
"datdedadsdwdssdwa".getBytes()
);
image = new Image(1L, "테스트 이미지", "12kl312nlk3".getBytes(), new Location("12.1234567", "12.1234566"));
positionedImageDTO = new PositionedImageDTO("테스트 이미지", content, "12.1234567", "12.1234566");
}
#Test
public void image_create_API_success() {
MultiValueMap<String, Object> parameters = new LinkedMultiValueMap<String, Object>();
parameters.add("fileName", "테스트 이미지");
parameters.add("file", content);
parameters.add("xIndex", "123");
parameters.add("yIndex", "454");
ResponseEntity<Image> responseEntity = sendFile(API_IMAGE_URI, parameters, Image.class);
assertThat(responseEntity.getBody().getName()).isEqualTo("테스트 이미지");
}
...
Controller CODE
#RestController
#RequestMapping("/api/image")
public class ApiImageController {
...
#PostMapping("")
public ResponseEntity<Image> create(#ModelAttribute PositionedImageDTO positionedImageDTO){
Image image = imageService.create(positionedImageDTO);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.setLocation(URI.create("/api/image/"+image.getId()));
return new ResponseEntity<>(image, headers, HttpStatus.CREATED);
}
...
}
DTO CODE
#Getter
#Setter
#NoArgsConstructor
#ToString
public class PositionedImageDTO {
#NotEmpty
private String fileName;
#NotEmpty
private MultipartFile file;
#NotNull
private String xIndex;
#NotNull
private String yIndex;
public PositionedImageDTO(String fileName, MultipartFile file, String xIndex, String yIndex) {
this.fileName = fileName;
this.file = file;
this.xIndex = xIndex;
this.yIndex = yIndex;
}
public String getExtentionFormat() {
return "." + file.getContentType().split("/")[1];
}
}

Java.lang.NullPointerException what's wrong

It says error in this method a null pointer Exception
#Test
public void showBookListPage() throws Exception {
List<Book> expectedBookList = bookService.findAll();
BookService bookService = mock(BookService.class);
when( bookService.findAll()).thenReturn(expectedBookList);
BookController bookController = new BookController(bookService);
MockMvc mockMvc = standaloneSetup(bookController).build();
mockMvc.perform(get(" /book/bookList"))
.andExpect(view().name("bookList"))
.andExpect(model().attributeExists("bookList"))
.andExpect(model().attribute("bookList", hasItems(expectedBookList.toArray())));
}
}
Other than that everything seems to be correct
This is the error I got after mocking the book service first before call
java.lang.IllegalStateException: missing behavior definition for the preceding method call:
BookService.findAll()
Usage is: expect(a.foo()).andXXX()
at org.easymock.internal.MockInvocationHandler.invoke(MockInvocationHandler.java:42)
at org.easymock.internal.ObjectMethodsFilter.invoke(ObjectMethodsFilter.java:94)
at com.sun.proxy.$Proxy134.findAll(Unknown Source)
at com.admintest.controller.BookControllerTest.showBookListPage(BookControllerTest.java:101)
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.springf
And this is my edit to the test method
#Test
public void showBookListPage() throws Exception {
BookService bookService = mock(BookService.class);
List<Book> expectedBookList = bookService.findAll();
when(bookService.findAll()).thenReturn(expectedBookList);
BookController bookController = new BookController(bookService);
MockMvc mockMvc = standaloneSetup(bookController).build();
mockMvc.perform(get(" /book/bookList"))
.andExpect(view().name("bookList"))
.andExpect(model().attributeExists("bookList"))
.andExpect(model().attribute("bookList", hasItems(expectedBookList.toArray())));
}
And by the way this is the controller
#RequestMapping("/bookList")
public String bookList(Model model) {
List<Book> bookList = bookService.findAll();
model.addAttribute("bookList", bookList);
return "bookList";
}
You have to mock the bookService before using it. Not after it's usage. So do the mocking of bookService in #BeforeMethod

mockit.internal.MissingInvocation Exception - using Spring , Jmockit

I am using JMockit with Spring and trying to verify some method from my service layer but i couldn't make it successful.
Find the below sample code
UserRepositoryImpl.java
package com.test.jmockit.JMockitsample.repository.impl;
import org.springframework.stereotype.Repository;
import com.test.jmockit.JMockitsample.User;
import com.test.jmockit.JMockitsample.repository.UserRepository;
#Repository("userRepository")
public class UserRepositoryImpl implements UserRepository{
/**
* Not yet implemented.
*
* #param User
* #return
*/
public User getLoggedInUser() {
User user = new User();
user.setUsername("admin");
user.setPassword("test123");
return user;
}
}
UserServiceImpl.java
/**
*
*/
package com.test.jmockit.JMockitsample.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.test.jmockit.JMockitsample.User;
import com.test.jmockit.JMockitsample.repository.UserRepository;
import com.test.jmockit.JMockitsample.service.UserService;
#Service("userService")
public class UserServiceImpl implements UserService{
#Autowired
private UserRepository userRepository;
public User getLoggedInUser() {
// TODO Auto-generated method stub
User user = userRepository.getLoggedInUser();
System.out.println("user service " + user.getUsername());
return user;
}
}
And my Test class
#ContextConfiguration(locations = { "classpath:/ApplicationContext.xml" })
#RunWith(SpringJUnit4ClassRunner.class)
public class JMockitVerificationTest {
#Tested
private UserService userService = new UserServiceImpl();
#Injectable
private UserRepository userRepository;
#Test
public void testUserServiceUserList() {
new Expectations() {
{
userRepository.getLoggedInUser();
result = new User("guest", "test123");
}
};
userService.getLoggedInUser();
new Verifications() {
{
userRepository.getLoggedInUser();
}
};
}
}
It's running success if i remove the verification block and getting expected result.
Trying to verify my method whether it is get invoked in service or not but getting below exception.
mockit.internal.MissingInvocation: Missing invocation of:
com.test.jmockit.JMockitsample.repository.UserRepository#getLoggedInUser()
on mock instance: com.test.jmockit.JMockitsample.repository.$Impl_UserRepository#425407
at com.test.jmockit.JMockitVerificationTest$2.<init>(JMockitVerificationTest.java:45)
at com.test.jmockit.JMockitVerificationTest.testUserServiceUserList(JMockitVerificationTest.java:42)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.lang.reflect.Method.invoke(Method.java:497)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.lang.reflect.Method.invoke(Method.java:497)
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.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:254)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89)
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.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:193)
at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:242)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:137)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:112)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189)
at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165)
at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85)
at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:115)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:75)
Caused by: Missing invocation
... 24 more
Don't know where i have done the mistake to make it success, thanks in advance.

Resources