0

I'm new to Spring and struggling with its complexity and opaque documentation. My question is How does one write a minimal @Value test?

Consider this test module, in MinimalValueTest.java.

import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import org.springframework.test.context.ActiveProfiles; @Component @ActiveProfiles("test") public class MinimalValueTest { @Value("${test.property}") public static String testProperty; @Test public void test() { if (testProperty == null) { System.out.println("*** FAILED ***"); } else { System.out.println("*** SUCCEEDED ***"); } // Unit tests will go here } } 

This test references this property defined in the src/test/resources/application.properties file:

test.property=a_test_property 

Running this outputs *** FAILED ***.

Extra credit: which Spring documentation best explains how to do this?

1
  • 2
    Make the testProperty non static, then it works. See baeldung.com/spring-inject-static-field and also what Sergey says below, annotate the test with @SpringBootTest Commented Feb 21, 2023 at 18:06

2 Answers 2

1

You need to annotate your test class with @SpringBootTest instead of @Component

Sign up to request clarification or add additional context in comments.

Comments

0

This works:

import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.stereotype.Component; import org.springframework.test.context.ActiveProfiles; /** * This simple example uses an @Value annotation. */ @SpringBootTest @ActiveProfiles("test") public class MinimalValueTest { @Value("${test.property}") String testProperty; @Test public void test() { Assertions.assertTrue(testProperty != null); Assertions.assertEquals("a_test_property", testProperty); } } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.