没有专用的字段设置器-单元测试旧版代码 [英] No Private Setter for Fields - Unit Testing Legacy Code

查看:54
本文介绍了没有专用的字段设置器-单元测试旧版代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

用于测试MyClass-

For testing MyClass -

我有:

 MyClass{
         private MyThing usedThing = new MyThing(); 

         public String funcToTest(){
               return usedThing.Fields.something.ToString(); 
         }
 }

问题: :这只是方法的一部分,但是我的问题是没有设置方法,或者没有更改产品代码,如何注入模拟的 MyThing 对象是否可以测试?

QUESTION: This is only a section of the method, but my question is without a setter, or without changing the prod code, how can I inject the mocked MyThing object into the test?

谢谢

推荐答案

您可以为此使用反射.这很糟糕,因为它允许您使用拥有类之外的私有方法或字段,从而破坏了封装.但是测试是一个有意义的用例.

You can use reflection for that. It is bad, because it allows you to use private methods or fields outside the owning class, breaking the encapsulation. But testing is a use case where it makes sense.

您可以通过以下方式从测试班级访问您的私有字段:

You can access you private field from your test class the following way :

MyClass myClass = new MyClass();
Field field = MyClass.class.getDeclaredField("usedThing");
field.setAccessible(true); // to allow the access for a private field
field.set(myClass, myMock);

这篇关于没有专用的字段设置器-单元测试旧版代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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