0

Hi I'm new to Java and Spring, and currently have a situation that is similar to this:

In Message.java

public class Message {
    final String text;
     
    public Message(@Value("${message.text}") String text) {
         this.text = text;
    }
}

In application.properties:

message.text = "This is some text."

Now, I have a test file where I want to write a test that checks the value of the String text, akin to something like

assertEquals(text, "This is some text.");

How would I go about doing this? It seems I can't manually invoke the constructor by doing new Message("...") because that overrides the @Value injection.

heim88
  • 1
  • @Andreas The linked question was not a duplicate because it is discussing how to manage field injection; OP's question here is about context binding. – chrylis -cautiouslyoptimistic- Jun 23 '21 at 01:16
  • 1
    @chrylis-cautiouslyoptimistic- Too bad you removed it, because if you actually read answers [#2](https://stackoverflow.com/a/41964308/5221149) and [#3](https://stackoverflow.com/a/51810713/5221149), not just #1, then you'd see that this question was fully answered by them *(Answer: Use `@TestPropertySource`)*. Just because the OP of that answer chose to accept #1, doesn't mean that that's the best answer. – Andreas Jun 23 '21 at 01:58

1 Answers1

0

The @Value annotation here is an instruction to the Spring container, so if you're wanting to test that it operates as expected, the only way to do that is to use SpringRunner or equivalent to actually start a context and feed it the value in question. Typically, this annotation isn't directly explicitly tested; rather, when the bean is covered as part of a medium-scale test like @SpringBootTest, its value will be set somewhere and is expected to be used in some business manner, the effect of which is tested.

chrylis -cautiouslyoptimistic-
  • 75,269
  • 21
  • 115
  • 152