Testing un-compilable code in NUnit - c#

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?

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));
}

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.

ConstructorInfo ci = typeof(MyClass).GetConstructor(Type.EmptyTypes);
Assert.IsNull(ci);

Check out this page on dynamically invoking constructors.

you could use reflection to check if there is a no arg constructor for the class and fail the test if there is

Yep. A good way would be to use reflection to try a parameterless constructor within a try/catch.

Related

C# Constructor - why default constructor is generated by compiler only if there is no constructor, instead of when there is no default constructor

According to MSDN's design guide for constructors,
"If you don’t explicitly declare any constructors on a type, many languages (such as C#) will automatically add a public default constructor. (Abstract classes get a protected constructor.)
Adding a parameterized constructor to a class prevents the compiler from adding the default constructor. This often causes accidental breaking changes."
Why not:
"If you don’t explicitly declare any default constructors on a type, many languages (such as C#) will automatically add a public default constructor. (Abstract classes get a protected constructor.)"
What is the reason behind this?
Because not all classes should be constructed parameterless.
Consider a class that is designed to implement the interface between your application and a file on disk. It would be very inconvenient having to handle the case where the object is constructed without specifying which file to manage.
As such, since the main point of creating a non-static class is that you want to create objects of it, you're spared having to add an empty parameterless constructor if that is all you want to have.
Once you start adding constructors at all, then the automagic is disabled and no default constructor will be provided.
If I define a custom constructor which means my object need initialising in a specific way e.g.:
class Customer
{
public Customer(string name) { this.Name = name; }
public string Name { get; }
}
If the compiler also added public Customer() then you could bypass the requirement to initialise a customer with a name.
If no constructor is present, there is no way to new up an instance of the class.
So, when you provide a constructor, there is at least one way to construct the class. If no constructor at all is provided, one is provided by default, so that you can actually build the class.
This answer's the question of why the default constructor exists, but not why it doesn't exist when you don't create your own parameterless constructor.
If a default constructor were to be provided when you've already provided one, this could lead to unintended consuming of the class. An example of this has been pointed out in another answer, but just as another:
public class Foo
{
private readonly IDbConnection _dbConnection;
public Foo(IDbConnection dbConnection)
{
if (dbConnection == null)
throw new ArgumentNullException(nameof(dbConnection));
_dbConnection = dbConnection;
}
public Whatever Get()
{
var thingyRaw = _dbConnection.GetStuff();
var thingy = null; // pretend some transformation occurred on thingyRaw to get thingy
return thingy;
}
}
If a default constructor were to be automatically created in the above class, it would be possible to construct the class without its dependency IDbConnection, this is not intended behavior and as such, no default constructor is applied.

Nunit test gives result OneTimeSetUp: No suitable constructor was found

I have an issue where NUnit is telling me: "No suitable constructor was found". What causes this? I also get another message: "Exception doesn't have a stacktrace". Both messages just repeat over and over again. Here's my code
[TestFixture]
public class SecurityServiceTests
{
private IContext stubIContext;
private ISecurityService securityService;
private IWindsorContainer windsorContainer;
public SecurityServiceTests(IContext stubIContext)
{
this.stubIContext= stubIContext;
}
[TestFixtureSetUp]
public void TestSetup()
{
//Mocks the database context
stubIContext= MockRepository.GenerateStub<IContext>();
var returnedList = new List<string>();
stubIContext.Stub(a => a.GetUserSecurities(null)).IgnoreArguments().Return(returnedList);
securityService = new SecurityService(windsorContainer);
}
[Test]
public void ControllerShouldGetUserGroupForCurrentUsers()
{
//Act
var action = securityService.CurrentUserFeatureList;
//Assert
Assert.IsNotNull(action);
}
}
You are trying to create a parameterized fixture, so you have a constructor taking a single argument. Contrary to the comment above, this is valid in both NUnit V2 and V3.
However, in order for NUnit to use that constructor, you have to give it an argument to be applied and you have not done so. You would do this by specifying
[TestFixture(someArgument)]
Probably, you are intending to do something like that by assigning a value to stubIContext in the TestFixtureSetUp. However, that can't work for two reasons:
It's not being supplied to the constructor and that's where your fixture needs it.
Anyway, construction of the object takes place before that setup method is called.
There are several ways to get the stub created before the fixture is instantiated, particularly in NUnit v3. However, I don't actually see why you need this fixture to be parameterized, since you are using a stub anyway.
Unless you have some other need for parameterization, not shown in the example, I would simply create the stub in the setup. My preference would be to use SetUp rather than TestFixtureSetUp. Creating stubs is not expensive, so there seems to be no reason to economize. However, if there are reasons not seen in the excerpt, TestFixtureSetUp can work as well.
Your SecurityServiceTests class needs to have a default constructor to be used as a TextFixture.
From the docs on TextFixture:
There are a few restrictions on a class that is used as a test fixture.
It must be a publicly exported type or NUnit will not see it.
It must have a default constructor or NUnit will not be able to construct it.
It's not clear anyway why you have a constructor in that class that accepts and sets IContext stubIContext as you then go on to mock that field in the Setup.
Remove the public SecurityServiceTests(IContext stubIContext) constructor and the tests will run.
Edit: it's slightly different in NUnit3, as pointed out by #Chris in the comments:
If no arguments are provided with the TestFixtureAttribute, the class must have a default constructor.
If arguments are provided, they must match one of the constructors.
What I had, it's constructor was protected and not public,
so Nunit couldn't found it.

c# - Throwing exceptions from attribute constructor

I found this article on the subject and tried the following:
public class FailerAttr : Attribute {
public FailerAttr(string s) {
throw new Exception("I should definitely fail!");
}
}
And in unit test project I have the following:
using Microsoft.VisualStudio.TestTools.UnitTesting;
[TestClass]
public class Test {
[TestMethod]
public void GoFail() {
// Make sure attribute will get initialized
new Failer();
}
private class Failer {
[FailerAttr("")]
public int Prop { get; set; }
}
}
When I run the test, it succeeds. So, the questions are:
Why it does not fail?
Is it really a bad idea to throw exceptions from attributes? Because I think I need to.
Some environment info (just in case it's relevant):
Unit tests are run via ReSharper's unit test runner (R# v8.2.0.2160)
Visual studio v11.0.61030.0
Since attributes are part of class definition available to you at runtime (it's also called "metadata" in geekspeak) CLR does not instantiate them unless some part of your program asks for them. This makes sense: why bother spending CPU cycles for something that nobody wants to access?
Because of this, the execution of the constructor will never happen unless you ask for that attribute.
Here is one way to ask for an attribute that would make your program fail:
var attr = Attribute.GetCustomAttribute(typeof(Failer).GetProperty("Prop"), typeof(FailerAttr));
This code makes CLR instantiate the FailerAttr, which triggers the exception.
Demo on ideone.
If you do not know the type of the attribute, you can retrieve all attributes at once with this call:
var allAttributes = Attribute.GetCustomAttributes(typeof(Failer).GetProperty("Prop"));
This causes an exception as well (demo).
Attributes are not converted to executable code, they're converted to metadata.
Metadata like this is not used during normal execution, it is only if you start using the metadata, like through reflection, that the attribute type comes back into play.
The constructor or any of the code in the attribute is not executed during compilation. Instead the type and the parameters to the constructor is serialized into the metadata, and only upon inspection using reflection will the constructor actually be executed.
In other words, if you intend this to fail at compile time then you can't.
Try looking for the attributes using reflection, depending on the attribute object is deserialized from the metadata, the constructor may or may not be invoked, but it will definitely not be invoked by just applying it to identifiers.

What does this C# code do?

public class AccountMembershipService : IMembershipService
{
private readonly MembershipProvider _provider;
public AccountMembershipService()
: this(null)
{
}
I took this bit of code from the AccountModels.cs class automatically created with the MVC3 project.
Can you explain what the 'this(null)' bit is doing?
It will call the single-argument constructor for AccountMembershipService, passing a null as the argument, before processing the body of the constructor you list.
From MSDN:
A constructor can invoke another constructor in the same object by using the this keyword. Like base, this can be used with or without parameters, and any parameters in the constructor are available as parameters to this, or as part of an expression.
More detail in section 17.10.1 (Constructor initializers) of the C# spec.
There is most likely another constructor in your class that looks like this:
public AccountMembershipService(MembershipProvider provider)
{
_provider = provider;
}
Your code calls this constructor first and passes null as the argument for provider, then executes the original constructor.
It calls a different constructor with a null argument.
The above answers are answering the question asked, but to go a bit further:
This is one technique we use for inversion of control and making unit testing possible.
Here are both constructors
public AccountMembershipService()
: this(null)
{
}
public AccountMembershipService(MembershipProvider provider)
{
_provider = provider ?? Membership.Provider;
}
The first constructor with :this(null) calls your 2nd constructor, passing null to the parameter provider.
One reason for doing this is to avoid duplication of logic. Suppose you did:
public AccountMembershipService()
{
_provider = Membership.Provider;
}
public AccountMembershipService(MembershipProvider provider)
{
_provider = provider;
}
While perfectly reasonable, if you change the name of _provider, or perhaps add some other initialization code, you'd have to modify it in 2 places. By calling :this(null), now all your work just happens in one place.
The reason we have 2 constructors is, by calling the default constructor, the static instance Membership.Provider gets used. Unfortunately it would be very difficult to unit test, because now we have dependencies on the membership providers, on the database, on having valid data, etc.
Instead, by creating the 2nd constructor, we can now pass in a mock MembershipProvider. This is an entirely different topic though, so if you're interested in how that works, feel free to ask another question.
It calls another constructor in your class and passes null as a parameter.
You can also write : base(...) to explicitly call a constructor in your base class.

C# Is there any benefit to assigning class properties in the class constructor?

For instance, if I have a class like this:
namespace Sample
{
public Class TestObject
{
private Object MyAwesomeObject = new MyAwesomeObject();
}
}
Is there any benefit to set it up so that the property is set in the constructor like this?
namespace Sample
{
public Class TestObject
{
private Object MyAwesomeObject;
public TestObject()
{
MyAwesomeObject = new MyAwesomeObject()
}
}
}
The two are (nearly) identical.
When you define the initializer inline:
private Object MyAwesomeObject = new MyAwesomeObject();
This will happen prior to the class constructor code. This is often nicer, but does have a couple of limitations.
Setting it up in the constructor lets you use constructor parameters to initialize your members. Often, this is required in order to get more information into your class members.
Also, when you setup values in your constructors, you can use your class data in a static context, which is not possible to do with inlined methods. For example, if you want to initialize something using an expression tree, this often needs to be in a constructor, since the expression tree is in a static context, which will not be allowed to access your class members in an inlined member initializer.
It makes it easier to do step by step debugging
It makes it easier to control the order in which you call constructors
It makes it possible to send parameters to the constructors based on some logic or passed in argument to the object you are working on.
Another nice property of initializing stuff at the declaration site is that doing so on readonly fields guarantees that the field is not observable in its default (initiaized to zero) state.
Here's my article on the subject:
http://blogs.msdn.com/ericlippert/archive/2008/02/18/why-do-initializers-run-in-the-opposite-order-as-constructors-part-two.aspx
The only benefit is that you can be a bit more dynamic in the constructor, where inline initialization requires that you only use static values for constructor arguments and such. For example, if MyAwesomeObject needs the value from a config file, you would have to set that in the constructor
Fields are initialized immediately
before the constructor for the object
instance is called. If the constructor
assigns the value of a field, it will
overwrite any value given during field
declaration.
See Fields (C# Programming Guide).
In your particular example, there's no advantage.
There is, however, lazy instantiation, which reduces your memory footprint in many cases:
namespace Sample
{
public Class TestObject
{
private Object m_MyAwesomeObject;
public TestObject()
{
}
public Object MyAwesomeObject
{
get
{
if (m_MyAwesomeObject == null)
m_MyAwesomeObject = new Object();
return m_MyAwesomeObject;
}
}
}
}
I like to keep all initialization for any class property whether primitive or object in the class constructor(s). Keeps the code easier to read. Easier to debug. Plus the intention of a constructor is to initialize your classes properties.
Also for clients developing against your classes it's nice to make sure that all your properties get a default value and all objects get created. Avoids the NullReferenceExceptions, when a client is using your class. For me putting this all in constructors makes it easier to manage.
I do not like to duplicate code, even if it is among a (hopefully) small number of constructors. To that end I tend to favor inline initialization wherever it makes sense.
Generally, requiring a non-default constructor ensures that the instance is in something other than the default state. This also allows immutable classes, which have their own advantages.

Categories