Janning Vygen
Janning Vygen

Reputation: 9222

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

I want to use WebTestClient in my tests. works like this:

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

    @Autowired
    private WebTestClient webTestClient;

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

But now I want to inject WebTestClient into a helper class:

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

Works, too. But Intellij is showing an error:

Could not autowire. No beans of 'WebTestClient' type found. more... (Strg+F1)

New info: The test runs fine in Intellij, but not when running with maven.

Here is a test project with the problem: https://github.com/kicktipp/demo

How can I use WebTestClient on my Helper class?

Upvotes: 2

Views: 2406

Answers (2)

eol
eol

Reputation: 24565

For what it's worth - I was able to fix this by simply specifying the AutoConfigureWebTestClient annotation explicitly:

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

}

Upvotes: 4

jbaddam17
jbaddam17

Reputation: 327

You have to build webTestClient before use it in tests
Use below, it will work

    @Autowired
    ApplicationContext context;

    @Autowired
    WebTestClient webTestClient;

    @Before
    public void setup() throws Exception {

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

Upvotes: 0

Related Questions