Home > Blockchain >  How to resolve @Value with resources in testing
How to resolve @Value with resources in testing

Time:09-30

I have the following service:

@Service
@RequiredArgsConstructor
public class Service {

    @Value("${filename}")
    private String filename;

    private final Repository repository;

}

And I'm trying to test it, for which I'd like to resolve filename with a specific value from application-test.yml:

filename: a beautiful name

So far, my test is the following:

@ExtendWith(MockitoExtension.class)
class ServiceTest {

    @Value("${filename}")
    private String filename;

    @Mock
    private Repository repository;

    @InjectMocks
    private Service service;

}

What can I do to initialize filename correctly?

CodePudding user response:

Since you're using Mockito, Spring isn't really involved in bootstrapping your test so things like @Value or application-test.yml mean nothing.

The best solution is to add the filename property in Service to your constructor (like repository):

@Service
public class Service {
    private final String filename;
    private final Repository repository;

    // Now you don't need @RequiredArgConstructor
    public Service(@Value("${filename}") String filename, Repository repository) {
        this.filename = filename;
        this.repository.repository;
    }
}

This allows you to inject any value you want by calling the constructor in your test:

@ExtendWith(MockitoExtension.class)
class ServiceTest {
    @Mock
    private Repository repository;

    private Service service;

    @BeforeEach
    void setUp() {
        // Now you don't need @InjectMocks
        this.service = new Service("my beautiful name", repository);
    }
}
  • Related