我是 Moq 的新手,我想进行这样的测试:
[Fact]
public void IsClientExternalForWebShouldReturnFalse()
{
// Arrange
var request = new Mock<HttpRequestBase>();
request.Setup(r => r.UserHostAddress).Returns(new Queue<string>(new[] { "127.0.0.1", "10.1.10.1" }).Dequeue);
var context = new Mock<HttpContextBase>();
context.SetupGet(c => c.Request).Returns(request.Object);
var service = new EnvironmentService(context.Object, null);
// Act / Assert
service.IsClientExternal.Should().BeFalse();
service.IsClientExternal.Should().BeFalse();
}
它抛出这个:
------ Test started: Assembly: SAIF.Services.Tests.dll ------
Test 'SAIF.Services.Tests.EnvironmentServiceTests.IsClientExternalForWebShouldReturnFalse' failed: System.InvalidOperationException : Queue empty.
at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
at System.Collections.Generic.Queue`1.Dequeue() at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
at System.Collections.Generic.Queue`1.Dequeue() at Moq.Extensions.InvokePreserveStack(Delegate del, Object[] args)
at Moq.MethodCallReturn`2.Execute(ICallContext call)
at Moq.Interceptor.Intercept(ICallContext invocation)
at Moq.Proxy.CastleProxyFactory.Interceptor.Intercept(IInvocation invocation)
at Castle.DynamicProxy.AbstractInvocation.Proceed()
at Castle.Proxies.HttpRequestBaseProxy.get_UserHostAddress()
Services\EnvironmentService.cs(54,0): at SAIF.Services.EnvironmentService.<get_IsClientExternal>b__3(String ip)
at System.Linq.Enumerable.Any[TSource](IEnumerable`1 source, Func`2 predicate)
Services\EnvironmentService.cs(54,0): at SAIF.Services.EnvironmentService.get_IsClientExternal()
EnvironmentServiceTests.cs(25,0): at SAIF.Services.Tests.EnvironmentServiceTests.IsClientExternalForWebShouldReturnFalse()
0 passed, 1 failed, 0 skipped, took 0.69 seconds (xUnit.net 1.9.1 build 1600).
实际测试代码:
public bool IsClientExternal
{
get { return IsWeb && !internalAddressRoots.Any(ip => httpContext.Request.UserHostAddress.StartsWith(ip)); }
}
但是,如果我只在它工作后才调用该服务,但该服务只获得第一个值。
此外,如果我调试并将鼠标悬停在 上httpContext.Request.UserHostAddress
,则值会更改。
有任何想法吗?
编辑#1
所以我发现了我认为的问题。这个问题是被测试的实际代码循环通过所有 ip 并调用UserHostAddress
. 我只需要弄清楚如何将字符串数组提供Returns()
给模拟函数。