0

I use Spring MVC and Spring boot to write a Restful service. This code works fine through postman.While when I do the unit test for the controller to accept a post request, the mocked myService will always initialize itself instead of return a mocked value defined by when...thenReturn... I use verify(MyService,times(1)).executeRule(any(MyRule.class)); and it shows the mock is not used. I also tried to use standaloneSetup for mockMoc, but it complains it can't find the mapping for the path "/api/rule". Could anybody help to figure out the problem?

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebAppConfiguration
public class MyControllerTest {

@Mock
private MyService myService;

@InjectMocks
private MyController myRulesController;

private MockMvc mockMvc;

@Autowired
private WebApplicationContext wac;

@Before
public void setup() {
    MockitoAnnotations.initMocks(this);
    this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
}

@Test
public void controllerTest() throws Exception{
    ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
    Long userId=(long)12345;

    MyRule happyRule = MyRule.createHappyRule(......);

    List<myEvent> mockEvents=new ArrayList<myEvent>();
    myEvents.add(new MyEvent(......));
    when(myService.executeRule(any(MyRule.class))).thenReturn(mockEvents);

    String requestBody = ow.writeValueAsString(happyRule);
    MvcResult result = mockMvc.perform(post("/api/rule").contentType(MediaType.APPLICATION_JSON)
            .content(requestBody))
            .andExpect(status().isOk())
            .andExpect(
                    content().contentType(MediaType.APPLICATION_JSON))
            .andReturn();
    verify(MyService,times(1)).executeRule(any(MyRule.class));

    String jsonString = result.getResponse().getContentAsString();

}
}

Below is my controller class, where MyService is a interface. And I have implemented this interface.

@RestController
@RequestMapping("/api/rule")
public class MyController {

@Autowired
private MyService myService;

@RequestMapping(method = RequestMethod.POST,consumes = "application/json",produces = "application/json")
public List<MyEvent> eventsForRule(@RequestBody MyRule myRule) {
    return myService.executeRule(myRule);
}
}
Compass
  • 5,867
  • 4
  • 30
  • 42
Nico
  • 21
  • 4

1 Answers1

1

Is api your context root of the application? If so remove the context root from the request URI and test. Passing the context root will throw a 404. If you intend to pass the context root then please refer the below test case. Hope this helps.

@RunWith(MockitoJUnitRunner.class)
public class MyControllerTest {

    @InjectMocks
    private MyController myRulesController;


    private MockMvc mockMvc;



    @Before
    public void setup() {

        this.mockMvc = standaloneSetup(myRulesController).build();
    }
    @Test
    public void controllerTest() throws Exception{
        ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
        MyController.User user = new MyController.User("test-user");
        ow.writeValueAsString(user);
        MvcResult result = mockMvc.perform(post("/api/rule").contentType(MediaType.APPLICATION_JSON).contextPath("/api")
                .content(ow.writeValueAsString(user)))
                .andExpect(status().isOk())
                .andExpect(
                        content().contentType(MediaType.APPLICATION_JSON))
                .andReturn();
    }


}

Below is the controller

/**
 * Created by schinta6 on 4/26/16.
 */
@RestController
@RequestMapping("/api/rule")
public class MyController {

    @RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
    public User eventsForRule(@RequestBody User payload) {

        return new User("Test-user");

    }


    public static class User {

        private String name;

        public User(String name){
            this.name = name;
        }

    }

}
sunshine
  • 158
  • 1
  • 10