schooner_101
schooner_101

Reputation: 319

Spring Boot @Value is not being populated..why?

I am trying to get a value from my application.properties in Spring Boot using @Value but no matter what I do it is always null.

I am doing this in my HTTPClient test class. I have tried using environment variables, propertySource, PostConstruct, using getters and setters, and anything else I could find online but it does not seem to be populating at all... My test class is in src/test/java and the application.properties is in src/test/resources. I do also have a application.properties in my src/main/java but that is in a completely different folder so it should not be affecting it.

Here is my code:

import static org.junit.Assert.*;
import java.io.IOException;
import java.util.Map;
import javax.annotation.PostConstruct;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.fluent.Request;
import org.apache.http.entity.ContentType;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ConfigurableApplicationContext;
import com.google.gson.Gson;
import com.nulogix.billing.configuration.EndPointTestConfiguration;
import com.nulogix.billing.mockserver.MockServerApp;

@SpringBootTest(classes = EndPointTestConfiguration.class)
public class HttpClientTest {
    @Value("${billing.engine.address}")
    private String billingEngineAddress;
    @Value("${billing.engine.port}")
    private String billingEnginePort;


    @PostConstruct
    private void customInit() {
        System.out.print(billingEngineAddress);
        System.out.print(billingEnginePort);

    }

    public static final String request_bad  = "ncs|56-2629193|1972-03-28|20190218|77067|6208|3209440|self|";
    public static final String request_good = "ncs|56-2629193|1972-03-28|20190218|77067|6208|3209440|self|-123|-123|-123|0.0|0.0|0.0|0.0|0.0|0.0|0.0";



    @Test
    public void test_bad() throws ClientProtocolException, IOException {
        // missing parameter

        String result = Request.Post("http://" + billingEngineAddress + ":" + billingEnginePort)
                .connectTimeout(2000)
                .socketTimeout(2000)
                .bodyString(request_bad, ContentType.TEXT_PLAIN)
                .execute().returnContent().asString();

        Map<?, ?> resultJsonObj = new Gson().fromJson(result, Map.class);

        // ensure the key exists
        assertEquals(resultJsonObj.containsKey("status"), true);
        assertEquals(resultJsonObj.containsKey("errorMessage"), true);

        // validate values
        Boolean status = (Boolean) resultJsonObj.get("status");
        assertEquals(status, false);
        String errorMessage = (String) resultJsonObj.get("errorMessage");
        assertEquals(errorMessage.contains("Payload has incorrect amount of parts"), true);

    }


    @Test
    public void test_good() throws ClientProtocolException, IOException {
        String result = Request.Post("http://" + billingEngineAddress + ":" + billingEnginePort)
                .connectTimeout(2000)
                .socketTimeout(2000)
                .bodyString(request_good, ContentType.TEXT_PLAIN)
                .execute().returnContent().asString();

        Map<?, ?> resultJsonObj = new Gson().fromJson(result, Map.class);

        // ensure the key exists
        assertEquals(resultJsonObj.containsKey("status"), true);
        assertEquals(resultJsonObj.containsKey("errorMessage"), false);
        assertEquals(resultJsonObj.containsKey("HasCopay"), true);
        assertEquals(resultJsonObj.containsKey("CopayAmount"), true);
        assertEquals(resultJsonObj.containsKey("HasCoinsurance"), true);
        assertEquals(resultJsonObj.containsKey("CoinsuranceAmount"), true);
        assertEquals(resultJsonObj.containsKey("version"), true);

        // validate values
        Boolean status = (Boolean) resultJsonObj.get("status");
        assertEquals(status, true);
        String version = (String) resultJsonObj.get("version");
        assertEquals(version, "0.97");

    }

}

I am getting the values from my application.properties to get the IP address and port and test my Request.post.

Here is my application.properties

server.port=9119
server.ssl.enabled=false
logging.config=classpath:logback-spring.xml
logging.file=messages
logging.file.max-size=50MB
logging.level.com.nulogix=DEBUG
billing.engine.address=127.0.0.1
billing.engine.port=9119
billing.engine.api.version=0.97
billing.engine.core.name=Patient_Responsibility

Upvotes: 0

Views: 1228

Answers (3)

schooner_101
schooner_101

Reputation: 319

So what solved my issue is copying over the application.properties from my main to my test/resources. I then used @PropertySource to change the value to test.properties, separating it from application.properties in main. I created a bean of values in my endpoint config and then auto wired it into my httpclient test class.

I also added in web environment in my SpringBootTest annotation to use the defined port in test.properties and to run the test with my endpoint config class and main app class. This caused the @value strings to be populated and not be null.

@Configuration
public class EndPointTestConfiguration {

    @Value("${billing.engine.address}")
    private String mockServerIP;
    @Value("${billing.engine.port}")
    private String mockServerPort;

    @Bean
    public String mockAddress() {
        String mockServerAddress = "http://" + mockServerIP + ":" + mockServerPort;
        return mockServerAddress;

    }



    @Bean
    public GetVersionEndPoint getVersionEndPoint() {
        return new GetVersionEndPoint();
    }

    @Bean
    public AnalyzeEndPoint analyzeEndPoint() throws JAXBException {
        return new AnalyzeEndPoint();
    }

    @Bean
    public PredictionEngineService predictionEngineService() {
        return new PredictionEngineService();
    }

    @Bean
    public String studyDetailDemo() throws IOException {
        File file = ResourceUtils.getFile("src/test/resources/study-details-demo.txt");
        String content = new String(Files.readAllBytes(file.toPath()));
        return content;
    }

    @Bean
    public String studyDetailSampleNormal() throws IOException {
        File file = ResourceUtils.getFile("src/test/resources/study-details-normal.txt");
        String content = new String(Files.readAllBytes(file.toPath()));
        return content;
    }

    @Bean
    public String studyDetailSampleCms() throws IOException {
        File file = ResourceUtils.getFile("src/test/resources/study-details-cms.txt");
        String content = new String(Files.readAllBytes(file.toPath()));
        return content;
    }

}
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT,classes = {EndPointTestConfiguration.class,MockServerApp.class
})
@PropertySource(value={"classpath:test.properties"}, ignoreResourceNotFound = true)
public class HttpClientTest {



    @Autowired
    private String mockAddress;


    public static final String request_bad  = "ncs|56-2629193|1972-03-28|20190218|77067|6208|3209440|self|";
    public static final String request_good = "ncs|56-2629193|1972-03-28|20190218|77067|6208|3209440|self|-123|-123|-123|0.0|0.0|0.0|0.0|0.0|0.0|0.0";



    @Test
    public void test_bad() throws ClientProtocolException, IOException {
        // missing parameter

        String result = Request.Post(mockAddress)
                .connectTimeout(2000)
                .socketTimeout(2000)
                .bodyString(request_bad, ContentType.TEXT_PLAIN)
                .execute().returnContent().asString();

        Map<?, ?> resultJsonObj = new Gson().fromJson(result, Map.class);

        // ensure the key exists
        assertEquals(resultJsonObj.containsKey("status"), true);
        assertEquals(resultJsonObj.containsKey("errorMessage"), true);

        // validate values
        Boolean status = (Boolean) resultJsonObj.get("status");
        assertEquals(status, false);
        String errorMessage = (String) resultJsonObj.get("errorMessage");
        assertEquals(errorMessage.contains("Payload has incorrect amount of parts"), true);

    }


    @Test
    public void test_good() throws ClientProtocolException, IOException {
        String result = Request.Post(mockAddress)
                .connectTimeout(2000)
                .socketTimeout(2000)
                .bodyString(request_good, ContentType.TEXT_PLAIN)
                .execute().returnContent().asString();

        Map<?, ?> resultJsonObj = new Gson().fromJson(result, Map.class);

        // ensure the key exists
        assertEquals(resultJsonObj.containsKey("status"), true);
        assertEquals(resultJsonObj.containsKey("errorMessage"), false);
        assertEquals(resultJsonObj.containsKey("HasCopay"), true);
        assertEquals(resultJsonObj.containsKey("CopayAmount"), true);
        assertEquals(resultJsonObj.containsKey("HasCoinsurance"), true);
        assertEquals(resultJsonObj.containsKey("CoinsuranceAmount"), true);
        assertEquals(resultJsonObj.containsKey("version"), true);

        // validate values
        Boolean status = (Boolean) resultJsonObj.get("status");
        assertEquals(status, true);
        String version = (String) resultJsonObj.get("version");
        assertEquals(version, "0.97");

    }

}

Upvotes: 2

DEBENDRA DHINDA
DEBENDRA DHINDA

Reputation: 1193

You can do as follows :

@RunWith(SpringRunner.class)
@SpringBootTest(classes={Application.class})
public class HttpClientTest {
.............
.................
}

Upvotes: 0

user9065831
user9065831

Reputation:

You need to move your application.properties to src/test/resource folder. For test, spring load application properties from this path.

Upvotes: 0

Related Questions