The context looks good. I like the way you solved the conflicting It
with aliases. I would argue that the Moq alias can be improved. Consider something sentence-like. For example, Param.Is<T>
or Value.Is<T>
.
Some notes, with code snippets, then the whole spec rewritten at the bottom.
Subject
The Subject can be the Scenario from the story. Plus, it gets rendered with your test run report (especially nice in the HTML report).
[Subject("Login Page")]
MSpec's creator, Aaron Jensen, has reverted from using the "With" syntax altogether. Context class names do not show up for any reports, so avoid spending time inventing a meaningful name.
public abstract class MembershipContext
Name the concrete spec class after the Given in your story. Especially since the base class name isn't reported anywhere, you could be losing half your context in the report! You should also avoid putting the name of the system under test in context class names. This makes your contexts friendlier to refactoring the system under test.
public class When_an_existing_user_enters_valid_credentials
And are often unnecessary. They lead to separation of the Arrange and Act phases. Use a base class for common field initialization, like setting up mocked dependencies. But, you should not mock behavior in a base class. And you should not put context-specific information in the base class. In your example, the username/password. This way, you can create a second context with invalid credentials.
Establish context = () =>
{
membership = new Mock<ISiteMembership>();
loginController = new LoginController(membership.Object);
};
It reduces the "ceremony" of the language in your test. You should place them below all of the MSpec specific delegates, as those parts of the spec tell most of the story.
static ActionResult result;
The spec here is an excellent example of establishing a global context MembershipContext
and inheriting it in a context specific to the spec (thus, the additional Establish
).
[Subject("Login Page")]
public class When_an_existing_user_enters_valid_credentials : MembershipContext
{
Establish context = () =>
{
membership
.Setup<bool>(m => m.Validate(
Param.Is<string>(s => s == username),
Param.Is<string>(s => s == password)))
.Returns(true);
};
Because of = () => result = loginController.Login(username, password);
It should_log_the_user_in;
It should_redirect_the_user_to_the_admin_panel;
It should_show_message_confirming_successful_login;
static ActionResult result;
const string username = "username";
const string password = "password";
}
public abstract class MembershipContext
{
Establish context = () =>
{
membership = new Mock<ISiteMembership>();
loginController = new LoginController(membership.Object);
};
protected static Mock<ISiteMembership> membership;
protected static LoginController loginController;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With