在不使用Autowire构造函数的情况下模拟服务

时间:2019-11-08 22:56:24

标签: java spring spring-boot junit junit5

我想编辑此代码以将模拟用于服务。这段代码可以正常工作:

@Service
public class BinCountryCheckFilterImpl {

    private RiskFilterService riskFilterService;
    private Terminals terminal;

    @Autowired
    public BinCountryCheckFilterImpl(Terminals terminal, RiskFilterService riskFilterService) {  
        this.terminal = terminal;
        this.riskFilterService = riskFilterService;
    }

    public void validateBinCountryCheckFilter(Terminals terminal) throws JAXBException, JsonProcessingException {

        List<RiskFilters> filter_list = riskFilterService.findRiskFiltersByTerminalIdAndType(terminal.getId(), "BinCountryCheckFilter");
    }
}

JUnit测试:

public class BinCountryCheckFilterImplTest    {

    @Test
    public void testBinCountryCheckFilterImpl() throws JsonProcessingException, JAXBException {
        //Arrange
        RiskFilterService riskFilterService = Mockito.mock(RiskFilterService.class);
        Terminals terminal = Mockito.mock(Terminals.class);

        BDDMockito.given(
            riskFilterService.findRiskFiltersByTerminalIdAndType(anyInt(), anyString()))
            .willReturn(riskFiltersList);

        int expectedInt = 11;
        String expectedString = "BinCountryCheckFilter";

        when(terminal.getId()).thenReturn(expectedInt);

        BinCountryCheckFilterImpl binCountryCheckFilterImpl = 
            new BinCountryCheckFilterImpl(terminal, riskFilterService);

        //Act
        binCountryCheckFilterImpl.validateBinCountryCheckFilter();

        //Assert
        then(riskFilterService)
          .should()
          .findRiskFiltersByTerminalIdAndType(expectedInt, expectedString);
    }    
}

此代码不起作用:

    @Service
public class BinCountryCheckFilterImpl {

    @Autowired
    @Qualifier("riskFilterService")
    private RiskFilterService riskFilterService;

    public Response validateBinCountryCheckFilter(Merchants merchant, Contracts contract, Terminals terminal,
              PaymentTransaction message, HttpServletRequest request) throws JAXBException, JsonProcessingException {
               ...........

    }

}

由于某些原因,在运行JUnit测试时,riskFilterService为null。有什么方法可以正确实施JUnit测试的服务吗? 就我而言,我不想从构造函数中调用terminal, riskFilterService

1 个答案:

答案 0 :(得分:0)

在使用字段注入而不是构造函数注入时,必须在测试用例中(最好在标记为@Before的方法中)调用以下语句来初始化模拟

MockitoAnnotations.initMocks(this);