I am starting to play around with xUnit and Moq and was wondering if I am doing it right.
Should I write tests like this:
[Fact]
public void ForWebShouldReturnDev()
{
// Arrange
var server = new Mock<HttpServerUtilityBase>();
server.SetupSequence(s => s.MachineName).Returns("t11466").Returns("localhost").Returns("webdev");
var context = new Mock<HttpContextBase>();
context.SetupGet(c => c.Server).Returns(server.Object);
var service = new EnvironmentService(context.Object, null);
// Act / Assert
service.GetApplicationEnvironment().Should().Be(ApplicationEnvironment.Dev);
service.GetApplicationEnvironment().Should().Be(ApplicationEnvironment.Dev);
service.GetApplicationEnvironment().Should().Be(ApplicationEnvironment.Dev);
}
Or more like this:
[Fact]
public void ForWebShouldReturnDev()
{
// Arrange
var server = new Mock<HttpServerUtilityBase>();
var context = new Mock<HttpContextBase>();
context.SetupGet(c => c.Server).Returns(server.Object);
var service = new EnvironmentService(context.Object, null);
// Act / Assert
foreach (var name in new string[] { "t11466", "localhost", "webdev" })
{
server.Setup(s => s.MachineName).Returns(name);
service.GetApplicationEnvironment().Should().Be(ApplicationEnvironment.Dev);
}
}
I know you are only supposed to test one unit of code per test, but when there are variables to the test is it OK to loop through asserts?
I am having trouble figuring out the best way to test these types of things.
For the record, below is the actual code under test:
// The constructor for the application environment
public EnvironmentService(HttpContextBase httpContext, IEnvironment environment)
{
this.environment = environment;
this.httpContext = httpContext;
}
private readonly Dictionary<ApplicationEnvironment, string> applicationEnvironments = new Dictionary<ApplicationEnvironment, string>() {
{ ApplicationEnvironment.Dev, "DEV" },
{ ApplicationEnvironment.Test, "TEST" },
{ ApplicationEnvironment.QA, "QA" },
{ ApplicationEnvironment.Prod, "PROD" }
};
public ApplicationEnvironment GetApplicationEnvironment()
{
var machine = IsWeb ? httpContext.Server.MachineName : environment.GetCommandLineArgs().First();
return applicationEnvironments.FirstOrDefault(x => machine.ToUpper().Contains(x.Value)).Key;
}
I have another question out there here regarding more specifics with Moq.
Are there any good resources out there for Moq, their documentation is pretty thin.