Ayala Ben-Zvi
Ayala Ben-Zvi

Reputation: 1

Spring boot application-test.properties not initializes inside the tested component

I'm writing a test for a component that takes values from the application.properties.

In the test itself the values are picked up correctly from the application-test.properies. I used @TestPropertySource(locations = "classpath:application-test.properties")

However in the tested class the values are NOT getting picked up and are null.

The test:

@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);
}

The Tested component:

@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;
}

How can I properly test this with application-test.properties?

Upvotes: 0

Views: 359

Answers (1)

Andy Wilkinson
Andy Wilkinson

Reputation: 116061

Your setup method is creating the instance of ArtifactAssociationService. This means that it isn't a Spring bean and, therefore, doesn't have any dependency injection performed. This includes injection into fields annotated with @Value.

If you want the @Value-annotated fields to have their values injected, you will have to make your ArtifactAssociationService instance a bean, for example by creating it using a @Bean method in a @Configuration class.

Upvotes: 1

Related Questions