我开始玩 xUnit 和 Moq 并且想知道我是否做得对。
我应该这样写测试:
[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);
}
或者更像这样:
[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);
}
}
我知道您应该每次测试只测试一个代码单元,但是当测试中有变量时,循环断言是否可以?
我无法找出测试这些类型事物的最佳方法。
作为记录,下面是被测的实际代码:
// 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;
}
关于起订量的更多细节,我还有另一个问题。
Moq 有什么好的资源吗,他们的文档很薄。