0

I'm using Spring and I want to create unit test using Spock. This is my class

@Service
public class TestService{
    @Value("${test.path:}")
   private String path;
}

Is it any way to mock this variable in Spock tests without runing spring context?

Mateusz Sobczak
  • 1,551
  • 8
  • 33
  • 67

1 Answers1

2

Considering you don't want to set up a Spring(Boot) test, either inject the value field using constructor injection:

@Service
public class TestService{
   private String path;

   public TestService(@Value("${test.path:}") String path) {
        this.path = path;
   }
}
...

TestService service = new TestService("testValue");

Or set the value using ReflectionTestUtils:

TestService service = new TestService();
ReflectionTestUtils.setField(service, "path", "somePath");
Michiel
  • 2,914
  • 1
  • 18
  • 27