MockServerClient field is always null with Springboot and Junit5

101 views Asked by At

I'm following the "Running MockServer via Spring TestExecutionListener @MockServerTest" from this official guide.

In my Junit5 test I want to instantiate a MockServerClient field. To isolate I created a new project with just this test class:

import org.example.MockConfig;
import org.junit.jupiter.api.Test;
import org.mockserver.client.MockServerClient;
import org.mockserver.springtest.MockServerTest;
import org.springframework.test.context.ContextConfiguration;

@MockServerTest
//@RunWith(SpringRunner.class) Not needed in JUnit5
@ContextConfiguration(classes = MockConfig.class)
public class MockTest {

    private MockServerClient client;

    @Test
    void name() {
        assert client != null; //it fails.
    }
}

gradle.build file:

plugins {
    id 'java'
}

group = 'org.example'
version = '1.0-SNAPSHOT'

repositories {
    mavenCentral()
}

dependencies {
    testImplementation 'org.springframework.boot:spring-boot-starter-test:3.2.1'
    testImplementation platform('org.junit:junit-bom:5.9.1')
    testImplementation 'org.junit.jupiter:junit-jupiter'
    testImplementation 'org.mock-server:mockserver-spring-test-listener-no-dependencies:5.15.0'
}

test {
    useJUnitPlatform()
}

According to the documentation, it should work. I auto wired the field but still fails.

Any clue or workaround that I can use?

Update

The following depency was added to gradle.build file for completeness:

testImplementation 'org.springframework.boot:spring-boot-starter-test:3.2.1'
1

There are 1 answers

3
rieckpil On

When using JUnit 5 (JUnit Jupiter to be precise), you need to add @ExtendWith(SpringExtension.class) to your test class in that case otherwise the MockServerTestExecutionListener will not be taken into account behind the scenes. With JUnit 4, @RunWith(SpringRunner.class) did the trick.

Try this:

@MockServerTest
//@RunWith(SpringRunner.class) -> JUnit 4
@ExtendWith(SpringExtension.class) // -> JUnit Jupiter (aka. JUnit 5)
@ContextConfiguration(classes = MockConfig.class)
public class MockTest {

    private MockServerClient client;

    @Test
    void name() {
        assert client != null; //it fails.
    }
}

For more theoretical input on the SpringExtension, you can refer to this article.