单元测试具有私有环境变量的类 [英] Unit testing a class with private environment variables
问题描述
问题是公共方法设置一些glassfish环境属性,环境变量是私有的。所以我无法将它设置在类之外,当我调用该方法的环境对象它抛出nullPointerException。
我要测试的类有,
@Resource(name =NameServiceEnvironment)
private属性nameServiceEnvironment;
public void setup(){
//设置环境。
属性environment = new Properties();
environment.setProperty(name.host,this.nameServiceEnvironment.getProperty(NAME_HOST));
environment.setProperty(name.port,this.nameServiceEnvironment.getProperty(NAME_PORT));
...}
所以现在对于nameServiceEnvironment,它会抛出空指针例外。
现在从测试类中我刚刚实例化了上述类,并调用了安装方法。
谢谢。
您始终可以访问,甚至是私人的方法。在您的测试中使用反思来访问私人财产 - 设置它们并继续使用。
I have an EJB which I want to unit test its public methods. I am testing EJB as a pojo. So I just have instantiate it and called the public method.
The problem is that public method sets some glassfish environment properties the environment variable is private. So I am not able to set it outside of the class and when I just call that public method for the environment object it throws nullPointerException.
The class that I want to test has,
@Resource(name="NameServiceEnvironment")
private Properties nameServiceEnvironment;
public void setup() {
// Set the environment.
Properties environment = new Properties();
environment.setProperty("name.host", this.nameServiceEnvironment.getProperty(NAME_HOST));
environment.setProperty("name.port", this.nameServiceEnvironment.getProperty(NAME_PORT));
...}
So now for nameServiceEnvironment it throws the null pointer exception.
Now from the test class I've just instantiated the above class and called the setup method.
Thanks.
You always have access, even to private methods. Use reflection in your test to gain access to the private properties - set them and get on with it.
这篇关于单元测试具有私有环境变量的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!