Overriding a property value in a Micronaut test

Viewed 2427

Using @Property on a test method seems to not take effect.

This is my application.yml

greeting: Hello

Application.java

@Controller
public class Application {

    @Property(name = "greeting")
    String greeting;

    @Get
    String hello() {
        return greeting + " World!";
    }

    public static void main(String[] args) {
        Micronaut.run(Application.class, args);
    }
}

Now test1 passes as expected, but test2 fails.

@MicronautTest//(rebuildContext = true)
public class DemoTest {

    @Inject
    @Client("/")
    HttpClient client;

    @Test
    void test1() {
        assertEquals(
                "Hello World!",
                client.toBlocking().retrieve(GET("/"))
        );
    }

    @Property(name = "greeting", value = "Bonjour")
    @Test
    void test2() {
        assertEquals(
                "Bonjour World!",
                client.toBlocking().retrieve(GET("/"))
        );
    }
}

Output

org.opentest4j.AssertionFailedError: expected: <Bonjour World!> but was: <Hello World!>

If I used rebuildContext = true, the HttpClient is not re-configured with the new port, and the second test fails with:

Connect Error: Connection refused: no further information: localhost/127.0.0.1:[some random port]

I put this code on GitHub at https://github.com/salah3x/micronaut-test-property-override

Is this a bug or I'm missing something?

1 Answers

It seems that manually refreshing the EmbeddedServer combined with @MicronautTest(rebuildContext = true) makes the tests pass.

@MicronautTest(rebuildContext = true)
public class DemoTest {

    @Inject
    @Client("/")
    HttpClient client;

    @Inject
    EmbeddedServer server;

    @Test
    void test1() {
        assertEquals(
                "Hello World!",
                client.toBlocking().retrieve(GET("/"))
        );
    }

    @Property(name = "greeting", value = "Bonjour")
    @Test
    void test2() {
        server.refresh();
        assertEquals(
                "Bonjour World!",
                client.toBlocking().retrieve(GET("/"))
        );
    }
}

But that's more of a workaround than a solution because the docs states that it should be automatically picked up.

Related