我正在为从application.properties中获取值的组件编写测试。
在测试本身中,可以从application-test.properies中正确获取值。 我用@TestPropertySource(locations =“ classpath:application-test.properties”)
但是在测试的类中,值不会被获取并且为空。
测试:
@RunWith(SpringJUnit4ClassRunner.class)
@TestPropertySource(locations = "classpath:application-test.properties")
public class ArtifactAssociationHandlerTest {
private InputStream inputStreamMock;
private ArtifactEntity artifactMock;
private ArtifactDeliveriesRequestDto requestDto;
@Value("${sdc.be.endpoint}")
private String sdcBeEndpoint;
@Value("${sdc.be.protocol}")
private String sdcBeProtocol;
@Value("${sdc.be.external.user}")
private String sdcUser;
@Value("${sdc.be.external.password}")
private String sdcPassword;
@Mock
private RestTemplate restClientMock;
@Mock
private RestTemplateBuilder builder;
@InjectMocks
private ArtifactAssociationService associationService;
@Before
public void setUp() throws IOException {
inputStreamMock = IOUtils.toInputStream("some test data for my input stream", "UTF-8");
artifactMock = new ArtifactEntity(FILE_NAME, inputStreamMock);
requestDto = new ArtifactDeliveriesRequestDto("POST",END_POINT);
MockitoAnnotations.initMocks(this);
associationService = Mockito.spy(new ArtifactAssociationService(builder));
associationService.setRestClient(restClientMock);
}
Tested组件:
@Component("ArtifactAssociationHandler")
public class ArtifactAssociationService {
@Value("${sdc.be.endpoint}")
private String sdcBeEndpoint;
@Value("${sdc.be.protocol}")
private String sdcBeProtocol;
@Value("${sdc.be.external.user}")
private String sdcUser;
@Value("${sdc.be.external.password}")
private String sdcPassword;
private RestTemplate restClient;
@Autowired
public ArtifactAssociationService(RestTemplateBuilder builder) {
this.restClient = builder.build();
}
void setRestClient(RestTemplate restClient){
this.restClient = restClient;
}
如何使用application-test.properties进行正确测试?
答案 0 :(得分:1)
您的setup
方法正在创建ArtifactAssociationService
的实例。这意味着它不是Spring bean,因此不执行任何依赖注入。这包括注入到用@Value
注释的字段中。
如果您希望注入带有@Value
的字段,则必须使ArtifactAssociationService
实例成为bean,例如,通过在其中使用@Bean
方法创建它@Configuration
类。