0

我正在为从 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);
}

测试组件:

@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 正确测试它?

4

1 回答 1

1

您的setup方法是创建ArtifactAssociationService. 这意味着它不是 Spring bean,因此没有执行任何依赖注入。这包括注入用@Value.

如果你想让@Value-annotated 字段的值被注入,你必须使你的ArtifactAssociationService实例成为一个 bean,例如通过使用类@Bean中的方法创建它@Configuration

于 2018-08-15T11:14:32.710 回答