Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing un-compilable code in NUnit

I have a class which for now should always have a certain member populated before it is valid. To enforce this, the class has no default constructor and instead has a constructor which accepts a value for that required member. The setup is similar to this below:

public class MyClass
{
  public string Owner { get; protected set; }

  public MyClass(string owner)
  {
    this.Owner = owner;
  }
}

Now I'd like to write a test to ensure that there is in fact no default constructor, so that if one gets added in the future, we are reminded of the reasons behind not having one and are forced to consider the impact of doing so. Although, obviously attempting to call the default constructor in a test won't just fail, it won't compile.

Is there a good way to pull off this kind of test without modifying my original class? If not, I suppose I could implement a default constructor which throws an exception. My only hesitation there is that calling the default constructor now becomes compilable code and then we must rely on other tests to ensure such code doesn't get written.

Thoughts?

like image 241
James Maroney Avatar asked Nov 28 '22 04:11

James Maroney


2 Answers

You could call Activator.CreateInstance(typeof(MyClass)) to try to run the default constructor, and assert that a MissingMethodException is thrown.

[Test]
[ExpectedException(typeof(MissingMethodException))
public void ShouldBeNoDefaultConstructorForMyClass()
{
    Activator.CreateInstance(typeof(MyClass));
}
like image 108
womp Avatar answered Dec 05 '22 17:12

womp


I would create a default constructor, mark it private and put your documentation there. Then your reasons for doing it won't be hidden off somewhere. You have to realize you'll be giving up some serialization functionality that requires the parameterless constructor.

like image 24
No Refunds No Returns Avatar answered Dec 05 '22 16:12

No Refunds No Returns