简体   繁体   中英

Spring Boot RestController testing returns 404

I'm trying to test my code (Spring-Boot project) of a RestController, but I always get 404. Here is what I have so far:

@RestController("/service")
public class ServiceInteractionController {

@Autowired
private PairingService pairingService;

@GetMapping("/registered/{sensorId}")
public ResponseEntity isSensorRegistered(@PathVariable String sensorId) {
    return ResponseEntity.ok(pairingService.isSensorRegistered(sensorId));
}

}

@RunWith(SpringRunner.class)
@WebMvcTest(ServiceInteractionController.class)
public class ServiceInteractionControllerTest {

@Autowired
private MockMvc mockMvc;

@MockBean
private PairingService pairingService;

@Before
public void setUp() {
    Mockito.when(pairingService.isSensorRegistered(TestConstants.TEST_SENSOR_ID))
            .thenReturn(true);
}

@Test
public void testIsSensorRegistered() throws Exception {
    mockMvc.perform(MockMvcRequestBuilders.get("service/registered/{sensorId}", TestConstants.TEST_SENSOR_ID))
            .andExpect(MockMvcResultMatchers.status().isOk());
}

}

The result always looks like this:

MockHttpServletRequest:
      HTTP Method = GET
      Request URI = service/registered/test123Id
       Parameters = {}
          Headers = []
             Body = <no character encoding set>
    Session Attrs = {}

Handler:
             Type = null

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = null

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 404
    Error message = null
          Headers = []
     Content type = null
             Body = 
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

java.lang.AssertionError: Status 
Expected :200
Actual   :404

What am I doing wrong? I already tried to initialize mockmvc directly in setUp method with standaloneSetup() and I have also used @SpringBootTest combined with @AutoConfigureMockMvc.

Does anyone have some useful hints? I use spring boot 2.1.4.

Thanks!

Don't you miss the "/" before the service/registered/{sensorId}?

mockMvc.perform(MockMvcRequestBuilders.get("service/registered/{sensorId}", TestConstants.TEST_SENSOR_ID))
        .andExpect(MockMvcResultMatchers.status().isOk()); 

Try changing this function to read:

@PathVariable 
@Test
public void testIsSensorRegistered(@PathVariable sensorId ) throws Exception {
    mockMvc.perform(MockMvcRequestBuilders.get("service/registered/{sensorId}", TestConstants.TEST_SENSOR_ID))
            .andExpect(MockMvcResultMatchers.status().isOk());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM