I am creating application in Spring Boot. I created service that looks that way:
@Service
public class MyService {
    @Value("${myprops.hostname}")
    private String host;
    public void callEndpoint() {
        String endpointUrl = this.host + "/endpoint";
        System.out.println(endpointUrl);
    }
}
This service will connect to REST endpoint to other application (developed also by me) that will be deployed along. That is why I want to customize hostname in application.properties file (-default, -qa, -dev).
My application builds and works just fine. I tested it by creating controller that calls this service, and it populates host field with correct property  from application.properties.
The problem occurs when I try to write test for this class. When I try this approach:
@RunWith(SpringRunner.class)
public class MyServiceTest {
    @Autowired
    private MyService myService;
    @Test
    public void callEndpoint() {
        myService.callEndpoint();
    }
}
i receive exception:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.ge.bm.wip.comp.processor.service.MyServiceTest': Unsatisfied dependency expressed through field 'myService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.ge.bm.wip.comp.processor.service.MyService' available: expected at least 1 bean which qualifies as autowire candidate.
And some more nested exception. I can post them if it will help. I suppose that for some reason SpringRunner does not launch this test in Spring context and therefore cannot see bean MyService.
Does anyone know how it can be fixed? I tried normal initialization:
private MyService myService = new myService();
but then host field is null
You have to annotate your test with @SpringBootTest as well.
Try:
@SpringBootTest
@RunWith(SpringRunner.class)
public class MyServiceTest {
    @Autowired
    private MyService myService;
    @Test
    public void callEndpoint() {
        myService.callEndpoint();
    }
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With