lundi 9 décembre 2019

Spring Boot mockmvc Testing When() thenReturn() stub returning Null

I am writing a unit tests to test REST API endpoints. I am using mockmvc to handle API testing and @injectmocks to load endpoint and @mock to mock the service layer. Below are snippets.

Test Class

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

Controller Class

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

Issue here is Mockito.when(cs.convertService(source, target, number)).thenReturn(dto); not returning a required DTO instead its returning a null.

Any suggestions on how to handle this ??

Aucun commentaire:

Enregistrer un commentaire