我正在尝试测试RestController的代码(Spring-Boot项目),但是我总是得到404。 这是我到目前为止的内容:
@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());
}
}
结果总是看起来像这样:
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
我在做什么错?我已经尝试过使用standaloneSetup()在setUp方法中直接初始化ockmvc,并且我还使用了@SpringBootTest和@AutoConfigureMockMvc。
有人有一些有用的提示吗?我使用的是Spring Boot 2.1.4。
谢谢!
答案 0 :(得分:0)
您是否在服务/注册/ {sensorId}之前错过了“ /”?
mockMvc.perform(MockMvcRequestBuilders.get("service/registered/{sensorId}", TestConstants.TEST_SENSOR_ID))
.andExpect(MockMvcResultMatchers.status().isOk());
答案 1 :(得分:-3)
尝试将此功能更改为:
Date