2016-02-10 17 views
5

我々は、いくつかのコントローラを持っている。このような何かを言う:Spring MVC統合テスト - ルックアップ要求のマッピングパス?

@Controller 
@RequestMapping("/api") 
public Controller UserController { 

    @RequestMapping("https://stackoverflow.com/users/{userId}") 
    public User getUser(@PathVariable String userId){ 
     //bla 
    } 
} 

我々は、このための統合テストを持っているが、言う:

@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); 
    } 
} 

我々はハード「/ API /ユーザー/を{コーディングを回避するにはどうすればよいですuserId} "テストでは?要求マッピングを名前でどのように調べることができますか。上記のリクエストマッピングのデフォルト名はUC#getUserである必要があります。

私が見たのは、MvcUriComponentsBuilderのようなものです。要求のコンテキスト内で使用する必要があるようです.jspsを使用してコントローラへのURLを生成します)。

これを処理する最善の方法は何ですか?コントローラ上の静的な文字列としてマッピングを公開する必要がありますか?私は少なくともそれを避けることを好むだろう。

+0

マッピングを使用したくない場合は、注釈を調べるために、クラスやメソッド名とリフレクションを使用してマッピングを抽出することができます。 – DavidA

答えて

1

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 ""; 
} 

私たちはそれを使用しますどのくらいの頻度知らないが、これは最高の私が見つけることができます。テストクラスで

使用法:

when().get(mapping(UserAccessController.class, "getProjectProfiles"), projectId) 
      .then().assertThat().body(....); 
3

ような何か:私は@DavidAが示唆されているようにやって、ちょうど反射を使用して終了

URI location = MvcUriComponentsBuilder.fromMethodCall(on(UserController.class).getUser("someUserId").build().toUri(); 
+0

ありがとうございます。メソッドの引数を提供する必要があるため(たとえ有効でなくても)、これを避ける傾向がありました。今、私は自分自身を推測しています... – Dan

関連する問題