[英]How do you test that a new instance of an object has been created?
I'm using C#, xUnit, and Moq for unit testing. 我正在使用C#,xUnit和Moq进行单元测试。 I have an object with a property of a complex type.
我有一个具有复杂类型属性的对象。 To "clear" the property and all its properties, I do this:
为了“清除”该属性及其所有属性,我这样做:
this.ComplexTypeInstance = new ComplexType();
Now I'm trying to assert that ComplexTypeInstance has been assigned to a brand new object. 现在,我试图断言ComplexTypeInstance已分配给一个全新的对象。 My first thought was to compare ComplexTypeInstance to new ComplexType() and see if they are equal.
我的第一个想法是将ComplexTypeInstance与新的ComplexType()进行比较,看看它们是否相等。 But to do something like that I think I'd have to override the equals operator.
但是要做类似的事情,我认为我必须重写equals运算符。 Is there any way to easily check that all properties are set to their defaults?
有什么方法可以轻松检查所有属性是否都设置为其默认值? Or is there a way to assert that I've newed up the object?
还是有办法断言我已经更新了对象?
Or is there a way to assert that I've newed up the object?
还是有办法断言我已经更新了对象?
Just compare the references between the old one and the new one using ReferenceEquals
. 只需使用
ReferenceEquals
比较旧版本和新版本之间的ReferenceEquals
。 If they are different, then the property has been replaced. 如果它们不同,则该属性已被替换。
var origInstance = this.ComplexInstance;
... // Some operation
Assert.False(object.ReferenceEquals(this.ComplexInstance, origInstance));
After thinking about this a bit, there were a few different scenarios I came up with to make it easier to test: 经过一番思考后,我提出了几种不同的方案以使其更易于测试:
Wrap the ComplexType in a factory sort of method. 用工厂的一种方法包装ComplexType。 I didn't like this b/c it just means one more class to create, and I wanted to avoid having such a simple factory.
我不喜欢这个b / c,它只是意味着要再创建一个类,并且我想避免拥有如此简单的工厂。
Extract and Override - Create a virtual method that allows me to remove the concrete dependency. 提取并覆盖-创建一个虚拟方法,使我可以删除具体的依赖关系。 Google "Extract and Override" if you have questions.
如果您有任何疑问,请使用Google“提取并覆盖”。 I don't like this b/c if you don't know the technique it can seem weird.
如果您不知道这种技术看起来很怪异,那么我不喜欢这个b / c。
Inject an anonymous function that returns a new instance of the object. 注入一个匿名函数,该函数返回对象的新实例。
A co-worker mentioned I could have also used Mark Seeman's SemanticComparison to compare my property to a new object. 一位同事提到我还可以使用Mark Seeman的SemanticComparison将我的属性与新对象进行比较。
I ended up going with the third option, injecting it through the constructor, though my IOC container couldn't resolve it easily and I had to spend a couple minutes trying to get it to resolve a binding for it. 我最后选择了第三个选项,将其通过构造函数注入,尽管我的IOC容器无法轻松解析它,我不得不花几分钟时间尝试使它解析它的绑定。 But I got it working pretty well.
但是我觉得它工作得很好。 Maybe I should have just created the factory.
也许我应该刚刚创建工厂。 But I'm glad I took out the dependency from the class.
但是我很高兴我从班级中消除了依赖性。 At first I didn't want to b/c it seemed so simple.
起初,我不想b / c看起来是如此简单。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.