Dan*_*Dan 6 spring-mvc rest-assured
我们有一些控制器,比如说:
@Controller
@RequestMapping("/api")
public Controller UserController {
@RequestMapping("/users/{userId}")
public User getUser(@PathVariable String userId){
//bla
}
}
Run Code Online (Sandbox Code Playgroud)
我们有一个集成测试,比如说:
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@SpringApplicationConfiguration(classes= MyApp.class)
@IntegrationTest("server:port:0")
public class UserControllerIT {
@Autowired
private WebApplicationContext context;
@Test
public void getUser(){
test().when()
.get("/api/users/{userId}", "123")
.then()
.statusCode(200);
}
}
Run Code Online (Sandbox Code Playgroud)
我们怎样才能避免在测试中对"/ api/users/{userId}"进行硬编码?我们如何按名称查找请求映射.上述请求映射的默认名称应为UC#getUser
我见过的唯一的东西就像MvcUriComponentsBuilder,它似乎要求它在请求的上下文中使用(因此它将在.jsps中用于生成控制器的URL).
处理这个问题的最佳方法是什么?我是否必须在控制器上将映射公开为静态字符串?我宁愿至少避免这种情况.
我最终按照@DavidA的建议做了,只是使用反射:
protected String mapping(Class controller, String name) {
String path = "";
RequestMapping classLevel = (RequestMapping) controller.getDeclaredAnnotation(RequestMapping.class);
if (classLevel != null && classLevel.value().length > 0) {
path += classLevel.value()[0];
}
for (Method method : controller.getMethods()) {
if (method.getName().equals(name)) {
RequestMapping methodLevel = method.getDeclaredAnnotation(RequestMapping.class);
if (methodLevel != null) {
path += methodLevel.value()[0];
return url(path);
}
}
}
return "";
}
Run Code Online (Sandbox Code Playgroud)
我不知道我们会多久使用它,但这是我能找到的最好的。
在测试类中的用法:
when().get(mapping(UserAccessController.class, "getProjectProfiles"), projectId)
.then().assertThat().body(....);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
573 次 |
| 最近记录: |