我有一个ApplicationProperties,可以在服务中使用它。当我在测试中模拟其余模板以测试该服务时,结果为java.lang.NullPointerException
,当我用网址替换applicationProperties.getBebusiness().getEndPointProvider()
时,测试通过了
@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());
}
}
答案 0 :(得分:0)
似乎您的spring bean没有实例化。您必须注释测试类,以告诉spring它必须初始化其上下文。尝试使用@SpringBootTest批注
答案 1 :(得分:0)
您可以使用import * as x from 'vue/dist/helper.js';
import { something } from 'vue/dist/helper.js';
批注,或者如果您不想运行Spring Boot上下文,则可以如下模拟您的配置类:
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
答案 2 :(得分:0)
您可以使用
@TestPropertySource(locations = "/other-location.properties")
或
@TestPropertySource(properties = "spring.datasource.max-active=30,
spring.datasource.initial-size=5")