Rest Spring Boot mockmvc测试When()thenReturn()存根返回Null

Rest Spring Boot mockmvc测试When()thenReturn()存根返回Null,rest,spring-boot,testing,junit,spring-boot-test,Rest,Spring Boot,Testing,Junit,Spring Boot Test,我正在编写一个单元测试来测试RESTAPI端点。我使用mockmvc处理API测试,使用@injectmock加载端点,使用@mock模拟服务层。下面是一些片段 测试类 @RunWith(SpringRunner.class) @SpringBootTest public class CurrencyConverterControllerTest { private MockMvc mockMvc; @InjectMocks private CurrencyConve

我正在编写一个单元测试来测试RESTAPI端点。我使用mockmvc处理API测试,使用@injectmock加载端点,使用@mock模拟服务层。下面是一些片段

测试类

@RunWith(SpringRunner.class)
@SpringBootTest
public class CurrencyConverterControllerTest {

    private MockMvc mockMvc;

    @InjectMocks
    private CurrencyConverterController controller;

    @Mock
    private CurrencyConverterService cs;

    @Before
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
        mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
    }

    @Test
    public void statusCheckTest() throws Exception {
        SendingResponseDTO dto = new SendingResponseDTO();
        String source = "GBP";
        String target = "USD";
        Double number = 32.56;
        dto.setSourceCurrency(source);
        dto.setTargetCurrency(target);
        dto.setNumber(number);
        dto.setTargetCurrencyValue(1.3136300664);
        dto.setTotalValue("$42.77");

        String apiURL = "/currency/converter/" + source + "/" + target + "/" + number;
        Mockito.when(cs.convertService(source, target, number)).thenReturn(dto);
        MvcResult result = mockMvc.perform(get(apiURL).contentType(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk()).andDo(print()).andReturn();
    }
@RestController
@RequestMapping("/currency")
@Validated
public class CurrencyConverterController {
    @Autowired
    CurrencyConverterService converterService;

    @Traceable
    @GetMapping(value = "/converter/{source}/{target}/{number}")
    public ResponseEntity<SendingResponseDTO> convertCurrency(
            @PathVariable("source") @CurrencyValidator @Pattern(regexp = "[a-zA-Z]{3}") @NotBlank @Size(min = 3) String source,
            @PathVariable("target") @CurrencyValidator @Pattern(regexp = "[a-zA-Z]{3}") @NotBlank @Size(min = 3) String target,
            @PathVariable("number") Double number) throws NotFoundException, InputsShouldNotBeSameException {

        if (source.equals(target)) {
            throw new InputsShouldNotBeSameException(
                    " Source Currency and Target currency should not be same for the conversion.");
        }
        SendingResponseDTO val = converterService.convertService(source.toUpperCase(), target.toUpperCase(), number);
        return ResponseEntity.ok().body(val);
    }
}
控制器类

@RunWith(SpringRunner.class)
@SpringBootTest
public class CurrencyConverterControllerTest {

    private MockMvc mockMvc;

    @InjectMocks
    private CurrencyConverterController controller;

    @Mock
    private CurrencyConverterService cs;

    @Before
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
        mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
    }

    @Test
    public void statusCheckTest() throws Exception {
        SendingResponseDTO dto = new SendingResponseDTO();
        String source = "GBP";
        String target = "USD";
        Double number = 32.56;
        dto.setSourceCurrency(source);
        dto.setTargetCurrency(target);
        dto.setNumber(number);
        dto.setTargetCurrencyValue(1.3136300664);
        dto.setTotalValue("$42.77");

        String apiURL = "/currency/converter/" + source + "/" + target + "/" + number;
        Mockito.when(cs.convertService(source, target, number)).thenReturn(dto);
        MvcResult result = mockMvc.perform(get(apiURL).contentType(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk()).andDo(print()).andReturn();
    }
@RestController
@RequestMapping("/currency")
@Validated
public class CurrencyConverterController {
    @Autowired
    CurrencyConverterService converterService;

    @Traceable
    @GetMapping(value = "/converter/{source}/{target}/{number}")
    public ResponseEntity<SendingResponseDTO> convertCurrency(
            @PathVariable("source") @CurrencyValidator @Pattern(regexp = "[a-zA-Z]{3}") @NotBlank @Size(min = 3) String source,
            @PathVariable("target") @CurrencyValidator @Pattern(regexp = "[a-zA-Z]{3}") @NotBlank @Size(min = 3) String target,
            @PathVariable("number") Double number) throws NotFoundException, InputsShouldNotBeSameException {

        if (source.equals(target)) {
            throw new InputsShouldNotBeSameException(
                    " Source Currency and Target currency should not be same for the conversion.");
        }
        SendingResponseDTO val = converterService.convertService(source.toUpperCase(), target.toUpperCase(), number);
        return ResponseEntity.ok().body(val);
    }
}
@RestController
@请求映射(“/currency”)
@验证
公共类CurrencyConverterController{
@自动连线
货币兑换服务兑换服务;
@可追溯
@GetMapping(value=“/converter/{source}/{target}/{number}”)
公共责任与货币(
@PathVariable(“source”)@CurrencyValidator@Pattern(regexp=“[a-zA-Z]{3}”)@NotBlank@Size(min=3)字符串源,
@PathVariable(“target”)@CurrencyValidator@Pattern(regexp=“[a-zA-Z]{3}”)@NotBlank@Size(min=3)字符串目标,
@PathVariable(“数字”)双倍数字)引发NotFoundException,InputsShouldNotBeSameException{
if(源等于(目标)){
抛出新输入shouldnotbesameeexception(
“转换时,源货币和目标货币不应相同。”);
}
sendingressponsedto val=converterService.convertService(source.toUpperCase(),target.toUpperCase(),number);
返回ResponseEntity.ok().body(val);
}
}
这里的问题是
Mockito.when(cs.convertService(source,target,number)),然后返回(dto)
不返回所需的DTO,而是返回null


关于如何处理这个问题有什么建议吗

尝试
Mockito.when(cs.convertService(Mockito.anyString(),Mockito.anyString(),Mockito.anyDouble())。然后返回(dto);
@AlanHay,非常感谢。这就像一个符咒:)确保在模拟调用中放入任何内容时使用模拟对象作为参数。