且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

单元测试具有私有环境变量的类

更新时间:2023-12-04 08:41:46

您始终可以访问,甚至是私人的方法。在您的测试中使用反思来访问私人财产 - 设置它们并继续使用。


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.