簡體   English   中英

在Spring Boot中的JUnit測試中創建bean時出錯

[英]Error creating bean in JUnit test in Spring Boot

我在Spring Boot中創建應用程序。 我創建了這樣的服務:

@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();

但是host字段為null

您還必須使用@SpringBootTest注釋您的測試。

嘗試:

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

    @Autowired
    private MyService myService;

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM