Using Spring mockMvc to test optional path variables

后端 未结 2 1967
猫巷女王i
猫巷女王i 2021-02-12 13:46

I have a method in Spring MVC with optional path variable. I am trying to test it for a scenario when optional path variable is not provided.

Snippet from Controller,

2条回答
  •  不思量自难忘°
    2021-02-12 14:18

    This is late but I faced recently this situation and thought this post would help others.

    In case of mocking endpoints with optional request param or path variable, you can specify it like this.

    Say I have a method with params as m1(String param1, String param2) called from controller.

    Where param 2 is an optional param for controller, so at runtime null would be passed if it is not passed.

    How to mock:

    Mockito.when(m1(Mockito.anyString(), Mockito.eq(null)).the return()
    

    Use Mockito.eq(null) in your test to pass it as null for optional param.

提交回复
热议问题