Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you test that a new instance of an object has been created?

I'm using C#, xUnit, and Moq for unit testing. 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. My first thought was to compare ComplexTypeInstance to new ComplexType() and see if they are equal. But to do something like that I think I'd have to override the equals operator. 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?

like image 604
Trevor Avatar asked Sep 18 '25 10:09

Trevor


1 Answers

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. If they are different, then the property has been replaced.

var origInstance = this.ComplexInstance;
... // Some operation
Assert.False(object.ReferenceEquals(this.ComplexInstance, origInstance));
like image 85
Ilian Avatar answered Sep 20 '25 23:09

Ilian