覆盖 Micronaut 测试中的属性值

sal*_*h3x 5 java micronaut

在测试方法上使用@Property似乎没有效果。

这是我的application.yml

greeting: Hello
Run Code Online (Sandbox Code Playgroud)

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

现在test1按预期通过,但test2失败了。

@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("/"))
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

输出

org.opentest4j.AssertionFailedError: expected: <Bonjour World!> but was: <Hello World!>
Run Code Online (Sandbox Code Playgroud)

如果我使用rebuildContext = true,则HttpClient不会使用新端口重新配置,并且第二个测试失败并显示:

Connect Error: Connection refused: no further information: localhost/127.0.0.1:[some random port]
Run Code Online (Sandbox Code Playgroud)

我将此代码放在 GitHub 上:https://github.com/salah3x/micronaut-test-property-override

这是一个错误还是我遗漏了一些东西?

sal*_*h3x 3

看来手动刷新EmbeddedServer组合@MicronautTest(rebuildContext = true)可以使测试通过。

@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("/"))
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

但这更多的是一种解决方法而不是解决方案,因为文档指出它应该被自动拾取。