2017-08-24 112 views
1

我在Spring Boot中创建应用程序。我创建的服务,看起来是这样:在Spring启动JUnit测试中创建bean时出错

@Service 
public class MyService { 

    @Value("${myprops.hostname}") 
    private String host; 

    public void callEndpoint() { 
     String endpointUrl = this.host + "/endpoint"; 
     System.out.println(endpointUrl); 
    } 
} 

此服务将连接到REST端点将被一起部署其他应用程序(由我还开发)。这就是为什么我想在application.properties文件(-default,-qa,-dev)中定制主机名。

我的应用程序构建和工作得很好。我通过创建调用此服务的控制器来测试它,并使用来自application.properties的正确属性填充host字段。

当我尝试为此课程编写测试时会出现问题。 当我尝试这个办法:

@RunWith(SpringRunner.class) 
public class MyServiceTest { 

    @Autowired 
    private MyService myService; 

    @Test 
    public void callEndpoint() { 
     myService.callEndpoint(); 
    } 
} 

我收到异常:

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.

而且一些嵌套异常。如果它可以帮助,我可以发布它们。 我想,由于某种原因SpringRunner不会在Spring上下文中启动此测试,因此无法看到Bean MyService。

有谁知道它是如何修复的?我想正常的初始化:

private MyService myService = new myService(); 

但随后hostnull

回答

2

你必须标注与@SpringBootTest测试也是如此。

尝试:

@RunWith(SpringRunner.class) 
@SpringBootTest 
public class MyServiceTest { 

    @Autowired 
    private MyService myService; 

    @Test 
    public void callEndpoint() { 
     myService.callEndpoint(); 
    } 
} 
相关问题