单元测试具有私有环境变量的类 [英] Unit testing a class with private environment variables

查看:471
本文介绍了单元测试具有私有环境变量的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个EJB,我想单位测试其公共方法。我正在测试EJB作为pojo。所以我只是实例化它,并称之为公共方法。



问题是公共方法设置一些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屋!

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