Spring Boot应用程序提供REST API。它有几个容器,经过单元测试。我已修改此应用程序以添加带有新PUT路径的新控制器,以上传文件。
当我使用mvn spring-boot:run
运行此应用程序时,我可以通过Postman访问新路由。但是,在我的单元测试中,我不能。
我的单元测试将WebApplicationContext自动装入测试并从中创建一个MockMVC,如下所示:
@SpringBootTest
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
class NewControllerTest {
@Autowired
private WebApplicationContext ctx;
// ... more autowirings ...
private MockMvc mockMvc;
@Before
public void setUp() {
mockMvc = standaloneSetup(ctx).build();
}
// ... actual test cases ...
}
然后,在测试用例中,我使用这样的路径:
mockMvc.perform(put("/newctrl/route/" + param + "/img.jpg")
.contentType("application/octet-stream").content(data))
.andExpect(status().isOk());
其中data
是byte[]
数组,param
是运行时生成的整数。
在其他几个测试用例中,API几乎以相同的方式加入。唯一的区别是在其他测试用例中,请求方法永远不是PUT,内容总是一个字符串。所有其他测试用例都有效。
然而,我的新测试会产生错误消息:
java.lang.AssertionError: Status expected:<200> but was:<404>
在日志中,我找到:
2016-11-27 20:01:22.263 WARN 15648 --- [ main] o.s.web.servlet.PageNotFound : No mapping found for HTTP request with URI [/newctrl/route/42/img.jpg] in DispatcherServlet with name ''
我使用mvn spring-boot:run
并将日志条目中的URL复制粘贴到Postman。我附上一张图片,瞧,它有效。
为什么我的测试不起作用?
编辑:摘自NewController:
@RequestMapping("/newctrl")
@RestController
@RequiredArgsConstructor(onConstructor = @__({@Autowired}))
public class NewController {
@RequestMapping(value = "/route/{param}/{filename:.+}")
public void theRoute(@PathVariable Long param, @PathVariable String filename,
HttpServletRequest request, HttpServletResponse response) throws IOException {
// ...
}
}