gpt4 book ai didi

java - 在测试中使用 ConfigurationProperties

转载 作者:行者123 更新时间:2023-12-01 19:07:09 26 4
gpt4 key购买 nike

我有一个 ApplicationProperties,我在我的服务中使用它。当我在测试中模拟其余模板来测试该服务时,当我将 applicationProperties.getBebusiness().getEndPointProvider() 替换为url,测试通过

@Configuration
@ConfigurationProperties(prefix = "application", ignoreUnknownFields = false)
public class ApplicationProperties { ...
}


@Service
public class ProviderServiceImpl implements ProviderService {

private final ApplicationProperties applicationProperties;

private final RestTemplate restTemplate;

public ProviderServiceImpl(ApplicationProperties applicationProperties, RestTemplate restTemplater) {
this.applicationProperties = applicationProperties;
this.restTemplate = restTemplate;
}

@Override
public List <ProviderDTO> getAllProviderFromBebusiness() {
final List <ProviderDTO> result = new ArrayList<>();
final ResponseEntity <String> responseEntity = restTemplate.getForEntity(
applicationProperties.getBebusiness().getEndPointProvider() + "&page=0&size=" + Integer.MAX_VALUE, String.class);
if (responseEntity.getStatusCodeValue() == 200) {}
return result;
}

}


public class ProviderServiceTest {

@Autowired
private ApplicationProperties applicationProperties;

@Rule
public MockitoRule mockitoRule = MockitoJUnit.rule();

@InjectMocks
private ProviderServiceImpl providerService;

@Test
public void givenMockingIsDoneByMockito_whenGetIsCalled_shouldReturnMockedObject() {
String provider = providerInit.buildProviderDTOWithIdFromBebusiness();
ResponseEntity <String> responseEntity = new ResponseEntity <String> (provider, HttpStatus.OK);
when(restTemplate.getForEntity(anyString(), ArgumentMatchers.any(Class.class)))
.thenReturn(responseEntity);
List<ProviderDTO> result = providerService.getAllProviderFromBebusiness();
assertEquals(200, responseEntity.getStatusCodeValue());
}

}

最佳答案

看来你的 spring beans 没有实例化。您必须注释您的测试类以告诉 spring 它必须初始化其上下文。尝试使用@SpringBootTest注释

关于java - 在测试中使用 ConfigurationProperties,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59529735/

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