I've started using MSpec recently, breaking classes into, Establish
, Because
and, It
.
Although I know how to use them, I'm not sure what goes into making them work.
I know they are delegates
Because of = () =>
{
};
But when looking at how delegates are defined:
public delegate void Print(int value);
It looks like Establish
, Because
and, It
are defined as delegates that return nothing (void
) and take no arguments.
Which makes sense, but how are Establish
, Because
and, It
distinguished from each other. I.e. What stops using It
instead of Establish
working just the same. And how does one of them know to use the other? i.e. It
uses Establish
Also they just get put in the class. What Invokes them?
public class foobar: setup
{
private static int engineId;
Because of = () =>
{
};
It should = () =>
{
};
}
See the above has the delegates initialized to these functions. But I don't know how they get called and why this isn't okay:
public class foobar: setup
{
private static int engineId;
It of = () =>
{
};
It should = () =>
{
};
}
Can anyone clarify this for me please?
Those delegates are of different types, even though they all have the same signature. So they are distinguished based on their type. For example suppose you have this class from example usage:
[Subject("Authentication")]
public class When_authenticating_a_user
{
Establish context = () =>
{
Subject = new SecurityService();
};
Cleanup after = () =>
{
Subject.Dispose();
};
static SecurityService Subject;
}
And now you want to imitate running that test. You use reflection to get all fields first, because both context
and after
are fields:
var fields = typeof(When_authenticating_a_user).GetFields(BindingFlags.Instance | BindingFlags.NonPublic);
Now you have bunch of fields, but which is which? You can distinguish them by field type. One is of type Establish
and another is of type Cleanup
(both are delegate types with the same signature):
var establish = fields.FirstOrDefault(c => c.FieldType == typeof(Establish));
var cleanup = fields.FirstOrDefault(c => c.FieldType == typeof(Cleanup));
And then you create an instance and execute them according to some logic:
var instance = Activator.CreateInstance(typeof(When_authenticating_a_user));
// get method
var establishMethod = (Establish)establish.GetValue(instance);
// execute
establishMethod();