0

I have this Step Definition which calls out CurrencyValidator. I wanted to create a unit test for it's isValid method


public class ValidationStepDefs {
    
    // Variables for the features Example
    private String enumName;
    private String ccy;
    
    private CurrencyValidator currencyValidator = new ValidCurrencyValidator();

    private String actualResult;
    
    @Given("valid currency are provided {string}")
    public void provideCcy(String ccy) {
        this.ccy = ccy;
    }
    
    @When("the CurrencyValidator.isValid was called")
    public void validCurrencyValidator() {

        boolean isCcyValid = currencyValidator.isValid(this.ccy, null);
        
        if(isCcyValid) {
            this.actualResult = "valid";
        } else {
            this.actualResult = "not valid";
        }
    }
    
    @Then("the result should be {string}")
    public void validation(String expectedResult) {
        assertEquals(expectedResult, actualResult);
    }   
    

This is the Currency Validator class. Which Autowired a service which gets all the currency from a database. But when I debug my code the service from CurrencyValidator class is getting a null as a value.


public class CurrencyValidator implements ConstraintValidator<Currency, String> {

    @Autowired
    SampleService service;

    @Override
    public boolean isValid(String currency, ConstraintValidatorContext context) {
        if (StringUtils.isNotBlank(currency)) {
            return getAllCurrencies().contains(currency);
        }

        return true;
    }


    private List<String> getAllCurrencies() {
        HashMap<String, Currency> CurrencyMap = refDataService.getKa4Currencies();
        List<String> currencies = new ArrayList<String>(CurrencyMap.keySet());
        return currencies;
    }
}


Zeke
  • 11
  • 3
  • Why are you creating a new instance of `CurrencyValidator ` in the `when` step? – Cisco Jan 26 '21 at 02:36
  • I wanted to test it's isValid method if I do `CurrencyValidator.isValid` i will need to change the isValid to a static type – Zeke Jan 26 '21 at 02:42
  • That doesn't make sense. If you're expecting `SampleService` to be autowired/injected, then manually creating a new instance isn't going to work. You're completely bypassing Spring's IOC by creating a new instance every time the `when` step is executed, – Cisco Jan 26 '21 at 03:03
  • I have changed the code to declare the `CurrencyValidator` in the StepDefs itself. So we don't create new instance everytime we do the `@When`. But upon testing it again SampleService is still returning null. – Zeke Jan 26 '21 at 03:09

0 Answers0