Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error creating bean in JUnit test in Spring Boot

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

like image 986
Zychoo Avatar asked Aug 24 '17 13:08

Zychoo


1 Answers

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();
    }
}
like image 144
Sasha Shpota Avatar answered Nov 15 '22 15:11

Sasha Shpota