1

say I have a class:

public class Person
{
  public string Name { get; set; }
  public int Age { get; set; }
}

and in a method I instantiate it:

public void SomeMethod(Person person)
{
   person = new Person()
}

Before the person was passed in it had values set.

What is the best way to assert that SomeMethod set the passed reference to a newly instantiated object?

All I can think of is to check all the nullable properties are empty and the non-nullable values have default values.

Is there a better way than this?

Marcel
  • 15,039
  • 20
  • 92
  • 150
user2005657
  • 607
  • 10
  • 20
  • `write a unit test to ensure a class has been newly instantiated?` say what? – Bala R Mar 12 '13 at 01:53
  • 2
    You don't trust that new calls the class constructor? Bizarre. – Peter K. Mar 12 '13 at 01:53
  • 1
    It's not that I don't trust it. I'm trying to test that it has been called. Essentially that the person has been reset. – user2005657 Mar 12 '13 at 01:55
  • Posting code that compiles may make question more clear... Possible checking "reference equal" between passed in person and resulting person is what you are looking for... – Alexei Levenkov Mar 12 '13 at 01:58
  • 1
    checking the reference equal would only test it was a different object. Not that it was a newly instantiated object. – user2005657 Mar 12 '13 at 01:59
  • I guess if you really want to check all the values to make sure they're set to a newly instantiated value, you could write a function which checks every field of Person and returns true or false – Memento Mori Mar 12 '13 at 02:00
  • What unit test framework are you using? I know with Moq, you can test that a method has been called: http://stackoverflow.com/a/347907/279516. That would make this question a duplicate. – Bob Horn Mar 12 '13 at 02:40
  • What is the context of the question? I can't believe you would be writing a unit test to verify the operation of the compiler, as that would be a magnificent waste of time. – theMayer Mar 12 '13 at 04:24
  • 1
    Just to be clear, SomeMethod will not set the caller's reference to a newly instantiated object. All it does is set its own, local variable to a newly instantiated object. Maybe this is causing some confusion? – Joe Daley Jun 04 '13 at 12:01
  • 1
    Even if the object is passed by reference, indeed it's a copy of the reference that is passed to a method, so it will not be set when outside of the method. If you want set a new value (instance of `Person`) to the reference passed to `SomeMethod` you need to use the `ref` keyword: `public void SomeMethod(ref Person person)` – polkduran Jun 04 '13 at 13:36

0 Answers0