Testing Incompatible Code in NUnit

I have a class that at the moment should always have a certain member filled up to its validity. To enforce this, the class does not have a default constructor and instead has a constructor that takes on a value for this required member. The setting is similar to the one below:

public class MyClass { public string Owner { get; protected set; } public MyClass(string owner) { this.Owner = owner; } } 

Now I would like to write a test to make sure that there is actually no default constructor, so if it is added in the future, we are reminded of the reasons why it does not have one, and are forced to take into account the impact of this. Although, obviously, an attempt to call the default constructor in the test will not just fail, it will not compile.

Is there a good way to take this test off without changing my original class? If not, I assume that I can implement a default constructor that throws an exception. My only doubt is that calling the default constructor now becomes compiled code, and then we must rely on other tests to ensure that such code is not written.

Thoughts?

+4
source share
6 answers

You can call Activator.CreateInstance(typeof(MyClass)) to try to run the default constructor and MissingMethodException that MissingMethodException .

 [Test] [ExpectedException(typeof(MissingMethodException)) public void ShouldBeNoDefaultConstructorForMyClass() { Activator.CreateInstance(typeof(MyClass)); } 
+10
source

I would create a default constructor, mark it as private, and post my documentation there. Then your reasons for this will not be hidden somewhere. You should understand that you will refuse some serialization functions that require a constructor without parameters.

+9
source
 ConstructorInfo ci = typeof(MyClass).GetConstructor(Type.EmptyTypes); Assert.IsNull(ci); 
+5
source

you can use reflection to check if there is no arg constructor for the class and failed the test if there is

0
source

Yeah. A good way would be to use reflection to try a parameterless constructor in try / catch.

0
source

Source: https://habr.com/ru/post/1301739/


All Articles