如何根据使用JUnit的环境变量来测试代码? [英] How to test code dependent on environment variables using JUnit?

查看:347
本文介绍了如何根据使用JUnit的环境变量来测试代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一块使用环境变量的Java代码,代码的行为取决于这个变量的值。我想用不同的环境变量值测试这个代码。我如何在JUnit中执行此操作?



我看过在Java中设置环境变量的一些方法,但是我对单元测试方面更感兴趣,特别是考虑到测试不应该相互干扰

解决方案

通常的解决方案是创建一个管理对这个环境变量的访问权限的类,然后你可以嘲笑你的测试类。

  public class Environment {
public String getVariable(){
return System.getenv ); //或任何
}
}

public class ServiceTest {
private static class MockEnvironment {
public String getVariable(){
return FOOBAR;
}
}

@Test public void testService(){
service.doSomething(new MockEnvironment());
}
}

测试中的类然后使用环境类,不直接来自System.getenv()。


I have a piece of Java code which uses an environment variable and the behaviour of the code depends on the value of this variable. I would like to test this code with different values of the environment variable. How can I do this in JUnit?

I've seen some ways to set environment variables in Java in general, but I'm more interested in unit testing aspect of it, especially considering that tests shouldn't interfere with each other.

解决方案

The usual solution is to create a class which manages the access to this environmental variable, which you can then mock in your test class.

public class Environment {
    public String getVariable() {
        return System.getenv(); // or whatever
    }
}

public class ServiceTest {
    private static class MockEnvironment {
        public String getVariable() {
           return "foobar";
        }
    }

    @Test public void testService() {
        service.doSomething(new MockEnvironment());
    }
}

The class under test then gets the environment variable using the Environment class, not directly from System.getenv().

这篇关于如何根据使用JUnit的环境变量来测试代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆