【问题标题】:Spring Testing - WebTestClient Could not autowire. No beans of 'WebTestClient' type foundSpring 测试 - WebTestClient 无法自动装配。找不到“WebTestClient”类型的 bean
【发布时间】:2019-06-14 19:57:51
【问题描述】:

我想在我的测试中使用 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?

【问题讨论】:

标签: java spring spring-boot testing intellij-idea


【解决方案1】:

您必须先构建 webTestClient,然后才能在测试中使用它
在下面使用,它会起作用的

    @Autowired
    ApplicationContext context;

    @Autowired
    WebTestClient webTestClient;

    @Before
    public void setup() throws Exception {

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

【讨论】:

    【解决方案2】:

    对于它的价值 - 我能够通过简单地明确指定 AutoConfigureWebTestClient 注释来解决这个问题:

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

    【讨论】:

      猜你喜欢
      • 2018-06-21
      • 2019-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-09
      • 1970-01-01
      • 1970-01-01
      • 2014-03-11
      相关资源
      最近更新 更多