gpt4 book ai didi

java - 不使用带有 Autowire 的构造函数的模拟服务

转载 作者:行者123 更新时间:2023-12-01 21:48:17 25 4
gpt4 key购买 nike

我想编辑此代码以使用模拟服务。这段代码运行良好:

@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

最佳答案

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

MockitoAnnotations.initMocks(this);

关于java - 不使用带有 Autowire 的构造函数的模拟服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58774731/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com