在junit中模拟System.getenv调用时遇到麻烦

编程入门 行业动态 更新时间:2024-10-24 06:33:58
本文介绍了在junit中模拟System.getenv调用时遇到麻烦的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试为Spring Boot应用程序使用junit和mockito(这是一个新功能)编写一个单元测试.基本上,在我的代码中,我已经为manifest.yml文件(用于部署)中的特定URL指定了一个环境变量,可以通过我的代码中的String URL = System.getenv("VARIABLE")访问该变量.但是,由于URL变量显然是未定义的,因此我在单元测试中遇到了很多麻烦.我在此处尝试了该解决方案,但是意识到,这仅用于模拟从实际测试本身调用的环境变量,而不是如果您依赖于可从代码访问的环境变量.

I'm trying to write a unit test with junit and mockito (very new to this) for a Spring Boot application. Basically in my code, I have specified an environment variable for a specific URL in a manifest.yml file (for deployment) that I can access through String URL = System.getenv("VARIABLE") in my code. I'm having a lot of trouble with my unit testing however, since the URL variable is obviously undefined. I tried the solution here, but realized this is only for mocking an environment variable if you're calling it from the actual test itself, not if you're relying on the environment variable being accessible from the code.

有什么方法可以设置它,以便在运行测试时可以设置可以在代码中访问的环境变量?

Is there any way to set it up so that when the test is run, I can set environment variables that can be accessed within the code?

推荐答案

您可以使用PowerMockito模拟静态方法.这段代码演示了模拟System类和对getenv()

You can use PowerMockito to mock static methods. This code demonstrates mocking the System class and stubbing getenv()

@RunWith(PowerMockRunner.class) @PrepareForTest({System.class}) public class Xxx { @Test public void testThis() throws Exception { System.setProperty("test-prop", "test-value"); PowerMockito.mockStatic(System.class); PowerMockito.when(System.getenv(Mockito.eq("name"))).thenReturn("bart"); // you will need to do this (thenCallRealMethod()) for all the other methods PowerMockito.when(System.getProperty(Mockito.any())).thenCallRealMethod(); Assert.assertEquals("bart", System.getenv("name")); String value = System.getProperty("test-prop"); Assert.assertEquals("test-value", System.getProperty("test-prop")); } }

我相信这可以说明您正在努力实现的目标. 使用PowerMockito.spy()可能有一种一种更优雅的方法来完成此操作,我只是不记得了.

I believe this illustrates what you are trying to accomplish. There may be a more elegant way to do this using PowerMockito.spy(), I just can't remember it.

对于在代码中直接或间接调用的System.class中的所有其他方法,您将需要执行thenCallRealMethod().

You will need to do thenCallRealMethod() for all the other methods in System.class that get called directly or indirectly by your code.

更多推荐

在junit中模拟System.getenv调用时遇到麻烦

本文发布于:2023-10-31 07:24:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1545423.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:麻烦   junit   System   getenv

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!