0

I have a @RestController defined for updating Person class as:

@RestController
@RequestMapping("/api/person")
class PersonRestController {

    @Autowired
    private IPersonService mPersonService;

    @PostMapping("/update")
    public Person updatePerson(@RequestBody Person person) {
        Optional<Person> personIfExists = mPersonService.findOneIfExists(person.id);
        if (!personIfExists.isPresent()) {
            throw new IllegalArgumentException();
        }
        return mPersonService.update(personIfExists.get());
    }
}

For brevity, lets assume that there exists a IPersonService and its proper implementation. The implementation is marked with @Service and is on the spring boot component scan path. I am using JMockit, TestNG and Spring MVC Test frameworks for testing this controller. I am also using GSON for converting Person object to JSON. Here is my test method:

@Test
    public void testUpdateFileDetails() throws Exception {
        Person person = new Person();
        person.id = "P01";
        person.name = "SOME_PERSON_NAME";
        person.age = 99;

        new Expectations() {{
            mockedPersonService.findOneIfExists("P01");
            result = new IllegalArgumentException();
        }};

        String personJson = new Gson().toJson(person);

        mvc.perform(post("/api/person/update").content(personJson))
                .andExpect(status().is4xxClientError());
    }

When I run this test case, I keep getting following exception:

Missing 1 invocation to:
        com.mytestapplication.services.api.IPersonService#getFileDetails("P01")
        on mock instance: com.mytestapplication.services.api.$Impl_IPersonServcie@8c11eee

        Caused by: Missing invocations
        at com.mytestapplication.rest.api.PersonRestControllerTest$2.<init>(PersonRestControllerTest.java:<line_number>)
        at com.mytestapplication.rest.api.PersonRestControllerTest.testUpdatePerson(PersonRestControllerTest.java:<line_number>)

Here refers to the line containing statement: new Expectations() {{ ... }}

Can you please help me in identifying the cause of this exception?

Prashant
  • 4,775
  • 3
  • 28
  • 47

1 Answers1

0

It looks like you need to provide mock for method call to

mPersonService.update(personIfExists.get());

which is return statement of your controller method.

Also I believe that method also has another method call to getFileDetails in the service.

So if provide mock for both these method calls, your test should work.

Japan Trivedi
  • 4,445
  • 2
  • 23
  • 44
  • Ok. But in my answer I'm asking to mock the method calls for IPersonServive.. Try to provide mock for method calls mPersonService.update and personIfExist.get() – Japan Trivedi Sep 17 '18 at 12:23