[英]Using VS2012 unit test is there a way to create an object and set its private fields without a constructor
So I'm getting in Unit Testing and I'm using the built-in framework with Visual Studio 2012 called Unit Test. 所以我正在进行单元测试,我正在使用Visual Studio 2012的内置框架,称为单元测试。
I've got some objects I need to mock up (I think..) 我有一些我需要模拟的对象(我想..)
There is a method that takes some parameters and returns an IEnumerable of resource objects which I want to compare in a deterministic way to a list/array of objects I create. 有一个方法接受一些参数并返回一个IEnumerable资源对象,我想以确定的方式将其与我创建的对象的列表/数组进行比较。 The problem the resource object I want to create has a constructor that takes arguments, performs its magic on them and then sets properties that I've marked as
我想要创建的资源对象的问题有一个构造函数,它接受参数,对它们执行魔术,然后设置我标记为的属性
{ get; private set; }
With the properties not having public setters, is there a way I can just set them so I can compare the result of the method to my 'oracle' list that I hand made? 由于没有公共设置器的属性,有没有办法我可以设置它们,所以我可以将方法的结果与我手工制作的'oracle'列表进行比较?
Taking a step back, 退后一步,
Thanks! 谢谢!
Does the comparison of the objects rely on data that is not publicly available (private or protected fields)? 对象的比较是否依赖于不公开的数据(私有或受保护字段)? If not, you could just assert that all fields are what you expect them to be.
如果没有,您可以断言所有字段都是您期望的字段。
I guess the right approach would be to have your resource implement an interface IResource that derives from IEquatable and implement that interface in a mock or stub object you create in your test method. 我想正确的方法是让您的资源实现一个从IEquatable派生的接口IResource,并在您在测试方法中创建的模拟或存根对象中实现该接口。
I am not convinced though that it is a good practice to unit test something as trivial as resource loading in depth. 我不相信尽管将资源加载作为微不足道的单元测试是一个很好的做法。 You could also just check if you get a certain number of items, none of the is null and assume everything works.
您还可以检查是否获得了一定数量的项目,没有一个是null并假设一切正常。 Might be easier than to adapt your unit test every time a resource changes.
每次资源变化时,可能比调整单元测试更容易。
See below answers to your questions: 请参阅以下问题的答案:
Now to your original question, you can use PrivateObject
to set property with private setter like done in below link: http://akurniaga.wordpress.com/tag/unit-test-privateobject-visual-studio/ 现在回答您的原始问题,您可以使用
PrivateObject
来设置属性,如下面的链接所示: http : //akurniaga.wordpress.com/tag/unit-test-privateobject-visual-studio/
You should also look at Moq or any other mocking framework for mocking the objects. 您还应该查看Moq或任何其他模拟框架来模拟对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.