0

I am new to SpringBoot so I hope to find some help here! :)

I have a class (please, see below), and I struggle to write unit tests for the methods that use the information shown below. The ExampleClass takes @Values from a yaml file.

My question:

  • How to set up configurable variables in a class and a test class so they pull values from the same place, so when I want to experiment with the values I do not have to go do a couple of different files/places to change the same values for a class and a test class.

  • If the answer is @Autowired - how to set up @Mock-s e.g. for private AmazonSQS exampleSQS and private AmazonSQSAsync exampleAsync within the @Autowired?

I have tried:

  • Setting up a test in src/test/resources app.yaml and using @TestPropertySource (walkaround version for yaml), and then @Value. That did not work because when the test enters a method in the ExampleClass, it loses the variables' values that I set up in TestExampleClass with @Value, and they reset to default(0, null etc.).

Code:

public class ExampleClass {
    private AmazonSQS exampleSQS;
    private AmazonSQSAsync exampleAsync;
    ...
    @Value("${a.b.var}")
        private int var;
    ...
}
alCodes
  • 1
  • 2
  • 2
    [We should prefer constructor injection over field injection](https://stackoverflow.com/questions/40737720/constructor-injection-vs-field-injection). I recommend reading a tutorial on constructor injection, e.g. [this one from `baeldung.com`](https://www.baeldung.com/constructor-injection-in-spring). – Turing85 Nov 22 '21 at 20:57

0 Answers0