2017-11-10 8 views
1

methodName("getEmployeeDetailsById")を型保証式に置き換えるにはどうすればよいですか?何とかクラスのメソッドに直接リンクします。それは可能ですか?春のjunitでメソッド呼び出しのtypsafeを確認するには?

@RunWith(SpringRunner.class) 
@WebMvcTest 
public class MyTest { 
    @Test 
    public void test() { 
     mockMvc 
     .perform(get("/employee/details/9816")) 
     .andExpect(handler().handlerType(EmployeeController.class)) 
     .andExpect(handler().methodName("getEmployeeDetailsById")); //TODO typesafe? 
    } 
あなたは@GetMappingアノテーションを持っているあなたのコントローラ内のメソッドを見つけることができます

答えて

1

は、あなたが期待を構築したいです静的な方法。

あなたはあなたの方法を達成するために、スプリングHandlerResultMatchers#methodCall & MvcUriComponentsBuilder#onを使用することができ、例えば:あなたは注意する必要が

mockMvc.perform(get("/employee/details/9816")).andExpect(
    handler().methodCall(on(EmployeeController.class).getEmployeeDetailsById(args)) 
    // args is any of the arbitrary value just to make the code to compile ---^ 
) 

しかし、一つのことはMvcUriComponentsBuilder#oncreate a proxy to be able to inspect the previous invocationsということです。ハンドラメソッドでStringビュー名を返すようにする場合はfinalであるため、Stringクラスのスーパータイプ(スーパーインターフェイスまたはスーパークラス)の戻り値の型をハンドラメソッドの戻り値の型にする必要があります。 cglibによってプロキシされています。例えば、

@RequestMapping("/foo") 
public Object handlerReturnViewName() { 
    // ^--- use the super type instead 
    return "bar"; 
} 
0

「/従業員/詳細/ {ID}」の値が(私は、必要に応じて調整し、何をここで使用したアノテーションと仮定しています)クラスのすべてのメソッドを介してそれを検索することによって:

private String findMethodName() { 
    List<Method> methods = 
     new ArrayList<>(Arrays.asList(EmployeeController.class.getMethods()); 
    for (Method method : methods) { 
     if (method.isAnnotationPresent(GetMapping.class)) { 
      GetMapping annotation = method.getAnnotation(GetMapping.class); 
      if(Arrays.asList(annotation.value()) 
          .contains("/employee/details/{id}") { 
        return method.getName(); 
       } 
     } 
    } 
} 

は、次に、あなたのmvcTestでこのメソッドを呼び出すことができます。私はあなたの意図を誤解していない場合は

.andExpect(handler().methodName(findMethodName())); 
関連する問題