PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, November 5, 2022

[FIXED] How to get properties from .env file in spring boot test

 November 05, 2022     environment-variables, java, junit5, spring-boot     No comments   

Issue

I am trying to setup tests for my spring-boot application. In regular execution I get some values from .env file that I've specified in run configuration and get them like so:

 @Value("${jdbc.url}")
 private String jdbcUrl;

But when I try to run the simplest of tests, it fails with the exception :

Failed to load ApplicationContext java.lang.IllegalStateException: Failed to load ApplicationContext........ Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaConfig': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'jdbc.url' in value "${jdbc.url}"

How do I load properties from the environment in SpringBootTest?

Here's my test:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = {App.class})
public class TestingWebApplicationTest {

    @Test
    public void contextLoads() {
    }

}

Solution

Try adding your property to this location /src/test/resources/application-test.properties

Add an @ActiveProfiles("test") annotation on the test class and it should be picked up. See screenshot below;

You can use a profile specific application-{profile}.properties file



Answered By - EfeyoPixel
Answer Checked By - Katrina (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing