簡體   English   中英

Spring 測試 - WebTestClient 無法自動裝配。 未找到“WebTestClient”類型的 bean

[英]Spring Testing - WebTestClient Could not autowire. No beans of 'WebTestClient' type found

我想在我的測試中使用 WebTestClient。 像這樣工作:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureWebTestClient
public class ControllerTest {

    @Autowired
    private WebTestClient webTestClient;

    @Test
    public void webtestClient () {
        assertNotNull(webTestClient);
    }
}

但現在我想將 WebTestClient 注入一個輔助類:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureWebTestClient
public class ControllerTest {

    @Autowired
    private Helper helper;

    @Test
    public void webtestClient () {
        helper.check();
    }
}

@Component
public class Helper {
    @Autowired
    private WebTestClient webTestClient;

    public void check() {
        assertNotNull(webTestClient);
    }
}

也有效。 但是 Intellij 顯示錯誤:

無法自動裝配。 未找到“WebTestClient”類型的 bean。 更多... (Strg+F1)

新信息:測試在 Intellij 中運行良好,但在使用 maven 運行時則不然。

這是一個有問題的測試項目: https : //github.com/kicktipp/demo

如何在 Helper 類上使用 WebTestClient?

對於它的價值 - 我能夠通過簡單地明確指定AutoConfigureWebTestClient注釋來解決這個問題:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureWebTestClient
public class MyTestClass {

}

在測試中使用它之前,您必須構建 webTestClient
在下面使用,它會起作用

    @Autowired
    ApplicationContext context;

    @Autowired
    WebTestClient webTestClient;

    @Before
    public void setup() throws Exception {

        this.webTestClient = WebTestClient.bindToApplicationContext(this.context).build();
    }

暫無
暫無

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

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