@Value 在单元测试中返回 null

2024-03-10

我有一个带有端点测试配置类和单元测试的 Spring Boot 应用程序来测试我的 http 客户端。我试图从位于我的 src/test 中的 application.properties 获取我的服务器地址和端口。(所有类都在我的 src/test 中。)

这是我的配置类代码:

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;

import javax.xml.bind.JAXBException;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ResourceUtils;
import com.nulogix.billing.service.PredictionEngineService;
import com.nulogix.billing.ws.endpoint.AnalyzeEndPoint;
import com.nulogix.billing.ws.endpoint.GetVersionEndPoint;
@Configuration
public class EndPointTestConfiguration {




    @Value("${billing.engine.address}")    
    private String mockAddress;

    @Value("${billing.engine.port}")
    private String mockPort;

    @Bean
    public String getAddress() {
        String serverAddress = "http://" + mockAddress + ":" + mockPort;
        return serverAddress;

    }

    @Bean
    public GetVersionEndPoint getVersionEndPoint() {
        return new GetVersionEndPoint();
    }

我用 @value 注释了 .properties 中的值,然后创建了一个用 bean 实例化的方法,以返回我的服务器地址字符串。

然后,我在 HttpClientTest 类中使用该字符串值:

import static org.junit.Assert.*;

import java.io.IOException;
import java.util.Map;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.fluent.Request;
import org.apache.http.entity.ContentType;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ConfigurableApplicationContext;

import com.google.gson.Gson;
import com.nulogix.billing.configuration.EndPointTestConfiguration;
import com.nulogix.billing.mockserver.MockServerApp;

@SpringBootTest(classes = EndPointTestConfiguration.class)
public class HttpClientTest {


    @Autowired
    EndPointTestConfiguration endpoint;


    public static final String request_bad  = "ncs|56-2629193|1972-03-28|20190218|77067|6208|3209440|self|";
    public static final String request_good = "ncs|56-2629193|1972-03-28|20190218|77067|6208|3209440|self|-123|-123|-123|0.0|0.0|0.0|0.0|0.0|0.0|0.0";
    //gets application context
    static ConfigurableApplicationContext context;

    //call mock server before class

    @BeforeClass
    static public void  setup(){
        SpringApplication springApplication = new SpringApplicationBuilder()           
                .sources(MockServerApp.class)
                .build();
        context = springApplication.run();
    }
    //shutdown mock server after class

    @AfterClass
    static public void tearDown(){
        SpringApplication.exit(context);
        }



    @Test
    public void test_bad() throws ClientProtocolException, IOException {
        // missing parameter
        String result = Request.Post(endpoint.getAddress())
                .connectTimeout(2000)
                .socketTimeout(2000)
                .bodyString(request_bad, ContentType.TEXT_PLAIN)
                .execute().returnContent().asString();

        Map<?, ?> resultJsonObj = new Gson().fromJson(result, Map.class);

        // ensure the key exists
        assertEquals(resultJsonObj.containsKey("status"), true);
        assertEquals(resultJsonObj.containsKey("errorMessage"), true);

        // validate values
        Boolean status = (Boolean) resultJsonObj.get("status");
        assertEquals(status, false);
        String errorMessage = (String) resultJsonObj.get("errorMessage");
        assertEquals(errorMessage.contains("Payload has incorrect amount of parts"), true);

    }


    @Test
    public void test_good() throws ClientProtocolException, IOException {
        String result = Request.Post(endpoint.getAddress())
                .connectTimeout(2000)
                .socketTimeout(2000)
                .bodyString(request_good, ContentType.TEXT_PLAIN)
                .execute().returnContent().asString();

        Map<?, ?> resultJsonObj = new Gson().fromJson(result, Map.class);

        // ensure the key exists
        assertEquals(resultJsonObj.containsKey("status"), true);
        assertEquals(resultJsonObj.containsKey("errorMessage"), false);
        assertEquals(resultJsonObj.containsKey("HasCopay"), true);
        assertEquals(resultJsonObj.containsKey("CopayAmount"), true);
        assertEquals(resultJsonObj.containsKey("HasCoinsurance"), true);
        assertEquals(resultJsonObj.containsKey("CoinsuranceAmount"), true);
        assertEquals(resultJsonObj.containsKey("version"), true);

        // validate values
        Boolean status = (Boolean) resultJsonObj.get("status");
        assertEquals(status, true);
        String version = (String) resultJsonObj.get("version");
        assertEquals(version, "0.97");

    }

}

我在 request.post 中使用它,我不想在我的 IP 地址和端口号中进行硬编码。

当我运行测试时它说

[ERROR]   HttpClientTest.test_bad:63 NullPointer
[ERROR]   HttpClientTest.test_good:86 NullPointer

但我不确定为什么它为空?我很确定我已经实例化了所有内容并且字符串已明确填充。

我的配置的包结构是 com.billing.mockserver,我的单元测试的包结构是 com.billing.ws.endpoint。

这是我的 application.properties

server.port=9119
server.ssl.enabled=false
logging.config=classpath:logback-spring.xml
logging.file=messages
logging.file.max-size=50MB
logging.level.com.nulogix=DEBUG
billing.engine.address=127.0.0.1
billing.engine.port=9119
billing.engine.api.version=0.97
billing.engine.core.name=Patient_Responsibility

您缺少对 Spring Boot 的基本了解。@Configurationclass 用于初始化其他 spring bean 和其他事物,并且是第一个被初始化的类。你不应该@Autowire @configuration班级。

在您的配置类中,您可以为用户名和密码创建 Spring bean,并在测试类中自动装配它,或者直接使用@Value在你的测试课中。

示例:在您的配置类中您正在创建 beanGetVersionEndPoint你可以autowire在你的测试课上。

更新2:

对于测试类,您需要添加application.properties文件输入src\test\resource

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

@Value 在单元测试中返回 null 的相关文章

随机推荐

  • 从 BottomNavigationView android 中删除动画/移动模式[重复]

    这个问题在这里已经有答案了 我正在构建一个应用程序 其中有一个 BottomNavigationView 一切正常 直到我进入活动 导航是这样的 问题是它有这个默认动画 所以它每次都会将活动元素推得比其他元素更高 另一个例子 所以我的问题是
  • 为什么响应中没有“Set-Cookie”标头?

    我发现有时浏览器无法从我的网站获取 cookie 所以我使用curl检查header 信息为 C Documents and Settings jack gt curl http localhost I HTTP 1 1 200 OK Ex
  • jQuery .click .animate 向下移动,然后向后移动

    到目前为止 我设法让它在点击时以 120 的增量向下移动 但我希望它向上和向下移动 而不是向下移动 我希望我已经解释了这一点 以便 某人 能够理解 如果我做对了 您将需要切换页脚的位置 这可以通过 toggle 函数来完成
  • 在 Python 中使用 lxml 将 XML 转换为字典

    StackOverflow 上似乎有很多用于将 XML 转换为 Python 字典的解决方案 但它们都没有生成我正在寻找的输出 我有以下 XML
  • Ruby 一元运算符“&”仅对方法参数有效

    你可能知道 Ruby 有一个速记运算符 这让我们可以轻松地转换Symbol to a Proc 例子 w a b c map upcase gt A B C 相当于 w a b c map c c upcase gt A B C 解释是 u
  • 为什么 gradle clean 任务会启动所有其他非默认任务?

    我已经设置并运行了 gradle 我的build gradle里面定义了 2 个任务 task setVersion println setVersion task setIntegrationEnv println setIntegrat
  • SignalR - 无法建立 SSL/TLS 安全通道的信任关系

    我正在尝试从服务器代码调用我的 signalR hub 方法 但它给了我一个错误 无法建立 SSL TLS 安全通道的信任关系 我的服务器端代码是这样的 private void InvokeNotification string meth
  • text() 和 string() 之间的区别

    有人可以解释一下 text 和 string 函数之间的区别吗 我经常将其与其他一起使用 但没有任何区别 两者都会获取xml节点的字符串值 有人可以解释一下text 和string 之间的区别吗 功能 I text 不是一个函数而是一个节点
  • Android 布局内的列表

    我正在开发一个 Android 应用程序 需要在布局 视图 内显示列表 表 我来自 iPhone dev objC land 我有一个应用程序 可以在视图 布局 内显示表格 列表 那么如何在我的布局中显示一个列表 并将其放置到指定位置 ce
  • 在 iPad 上滚动 iframe [重复]

    这个问题在这里已经有答案了 可能的重复 IFRAME 和 iPad 上的 Safari 用户如何滚动内容 https stackoverflow com questions 4599153 iframes and the safari on
  • 如何在 Swift 中压缩展开多个选项?

    我想解开这 6 个可选变量 如果它们为空 我想给它们一个空字符串值 这样我就可以将这些变量打包到发送到 API 的参数数组中 我仍然是 Swift 的初学者 这是我理解如何实现这一点的唯一最简单的方法 但我内心的编码员说这看起来很多余 而且
  • 错误:无法在此小部件上方找到正确的提供者< >

    我看不出我在下面做错了什么 但它抛出了一些提供程序错误和构建上下文 发生这种情况是因为您使用了BuildContext不包括提供者 你的选择 有以下几种常见场景 您在您的目录中添加了一个新的提供商main dart并执行热重载 要修复 请执
  • 如何清除 Eclipse Indigo 的缓存

    我想知道清除 Eclipse Indigo 缓存的标准方法是什么 您可以在启动 eclipse 时使用 clean 参数 例如 C eclipse eclipse exe vm C Program Files Java jdk1 6 0 2
  • 如何使用 Moles 通过 LINQ 从表中重定向选择?

    我有一个名为 订阅 的表 我想将该表中的任何 LINQ 选择重定向到 Moles lambda 以便从该表中只返回 3 行 基本上我想绕过对数据库的调用 到目前为止 我的代码如下所示 lazy loader is here to handl
  • 将现有的 C++(.h 和 .cpp)文件转换为 Android 的 java [关闭]

    Closed 此问题正在寻求书籍 工具 软件库等的推荐 不满足堆栈溢出指南 help closed questions 目前不接受答案 我正在 Eclipse 下为 Android 进行开发 我有一些 C h 和 cpp 文件希望在我的 A
  • Visual Studio 2015 发布 Web 仅具有自定义选项

    我正在使用 Visual Studio 2015 进行网络项目的网络发布 但似乎网络发布配置文件中的几个选项丢失了 此链接中应该包含选项使用 Visual Studio 2015 通过 Web 部署发布到 IIS http docs asp
  • 如何防止更改数组或对象的值

    我是 Java 初学者 在开发程序时 我使用构造函数创建了一个对象 并以变量作为参数 但是 当我在创建对象后更改变量的值时 我的对象具有第二个值而不是第一个值 我不希望我的对象改变值 我该怎么办 public class Person pu
  • Twitter Bootstrap - 全宽背景(图片)

    我目前正在进行一个项目 正在尝试很棒的 Twitter Bootstrap 包括响应式网格 除了一个问题之外 一切都运行良好 你如何给予 container 包含网格 背景颜色 例子 div class container green di
  • 每个请求上的 51Degrees 重新加载会减慢 ASP.NET MVC 的速度

    添加 51Degrees 移动检测库后 我的 ASP NET MVC 3 项目速度慢得像爬行一样 51Degrees 日志文件定义为
  • @Value 在单元测试中返回 null

    我有一个带有端点测试配置类和单元测试的 Spring Boot 应用程序来测试我的 http 客户端 我试图从位于我的 src test 中的 application properties 获取我的服务器地址和端口 所有类都在我的 src