简体   繁体   English

Junit 测试使用 ConfigProperties 注入 object 是 null

[英]Junit testing using ConfigProperties injected object is null

I have a Quarkus application, and I want to test one part of it.我有一个 Quarkus 应用程序,我想测试它的一部分。 That part is using kafka streams, and I do not want to connect to the network during testing, so I am not using the @QuarkusTest flag.那部分正在使用 kafka 流,我不想在测试期间连接到网络,所以我没有使用@QuarkusTest标志。

Instead I would use MockProcessorContext and the KafkaStreams junit testing approach.相反,我会使用MockProcessorContextKafkaStreams junit 测试方法。

As I am using a Transformer object, I need to use the same topic name throughout, so I have put the topics in an @ConfigProperties class (simplified example):由于我使用的是变压器 object,因此我需要始终使用相同的主题名称,因此我将主题放在@ConfigProperties class 中(简化示例):

@ConfigProperties(prefix = "test")
public class AppConfiguration {

    public TopicsConfig topics;
    public StoresConfig stores;

    public static class TopicsConfig {
        public String first = "first-topic";
        public String second = "second-topic";
    }
    
    public static class StoresConfig {
       public String first = "first-store";
    }
}

Then in my junit test class I @Inject this as I would normally in my application然后在我的 junit 测试 class 中,我像在我的应用程序中通常那样@Inject

@Inject
AppConfiguration config

The problem I have is that when I come to use it in my setup function, it is always null .我遇到的问题是,当我在我的设置 function 中使用它时,它总是null

@BeforeEach
public void setUp() {
   config == null
}

I do not know how to get around this - I don't want to use @QuarkusTest as I do not need to run the application and connect to all my servers.我不知道如何解决这个问题——我不想使用@QuarkusTest ,因为我不需要运行应用程序并连接到我的所有服务器。

Help and advice please!请帮助和建议!

If you want to use injection inside your test, you need to use @QuarkusTest as your need something to intiantiate your beans and make the injection happens.如果你想在你的测试中使用注入,你需要使用@QuarkusTest ,因为你需要一些东西来初始化你的bean并让注入发生。 And this is the role of the bean factory of Quarkus (Arc).而这就是 Quarkus(Arc)的 bean factory 的作用。

So there is no other way than making your test a Quarkus test via @QuarkusTest .因此,除了通过@QuarkusTest使您的测试成为 Quarkus 测试之外别无他法。

Another solution would be to use Mockito and mock the object instead of injecting it inside your test.另一种解决方案是使用 Mockito 并模拟 object 而不是将其注入测试中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM