【问题标题】:Overriding a property value in a Micronaut test在 Micronaut 测试中覆盖属性值
【发布时间】:2020-10-20 00:51:23
【问题描述】:

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

这是我的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);
    }
}

现在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("/"))
        );
    }
}

输出

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

如果我使用rebuildContext = trueHttpClient 不会重新配置新端口,第二次测试失败:

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

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

这是一个错误还是我遗漏了什么?

【问题讨论】:

  • 如果您将@Property(name = "greeting", value = "Bonjour") 添加到测试类(而不是测试中的方法),这会影响您的一个或两个测试方法吗?
  • @JeffScottBrown 将其添加到测试类会影响两个测试,因此test1 失败而test2 通过

标签: java micronaut


【解决方案1】:

似乎手动刷新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("/"))
        );
    }
}

但这更像是一种解决方法而不是解决方案,因为docs 声明它应该被自动拾取。

【讨论】:

  • 可能是一个@BeforeEach setup-method 在每个测试方法之前运行server.refresh() 是一个可行的选择。
猜你喜欢
  • 1970-01-01
  • 2019-04-07
  • 1970-01-01
  • 2017-12-14
  • 2019-03-20
  • 2018-07-12
  • 2019-04-04
  • 2016-08-07
  • 2015-10-28
相关资源
最近更新 更多