【发布时间】:2012-04-10 15:59:40
【问题描述】:
我正在用 C# 编写一个服务器组件并使用 Pex 进行单元测试。
我有一个针对特定方法的复杂参数化单元测试。现在事实证明,只要我添加了某个断言块,一些 pex 探索运行就会失败,并在我的方法的最后一行(就在括号中)出现 NullReferenceException。当我调试失败的运行时,它运行得非常好。
是我弄错了还是 pex 中的错误?
谢谢!
[PexMethod]
public Task Start(CancellationToken cancellationToken,
int workingEndpoints, // endpoints that run succesfully
int failingEndpoints, // endpoints that fail immidiatly
int brokenEndpoints) // endpoints that return null for their task
{
PexAssume.IsTrue(workingEndpoints >= 0);
PexAssume.IsTrue(failingEndpoints >= 0);
PexAssume.IsTrue(brokenEndpoints >= 0);
PexAssume.IsTrue(workingEndpoints + failingEndpoints + brokenEndpoints >= 1);
// create fake endpoints based on the count
List<IHostEndpoint> fakeEndpoints = new List<IHostEndpoint>();
Exception failedTaskException = new Exception();
// Create a few endpoint stubs for testing purposes and add them to the list (commented away for relevance)
// create and start the host
Host host = new Host(fakeEndpoints.ToArray());
Task result = host.Start(cancellationToken);
PexAssert.IsNotNull(result);
if (failingEndpoints > 0 || brokenEndpoints > 0)
{
PexAssert.IsNotNull(result.Exception);
int failedEndpointExceptionCount = 0;
int brokenEndpointExceptionCount = 0;
result.Exception.Flatten().Handle(innerException =>
{
if (innerException == failedTaskException)
failedEndpointExceptionCount++;
else
brokenEndpointExceptionCount++;
return true;
});
// after one broken endpoint, the run method should stop starting more endpoints
int brokenEndpointExpectedCount = Math.Min(1, brokenEndpoints);
PexAssert.AreEqual(failedEndpointExceptionCount, failingEndpoints);
PexAssert.AreEqual(brokenEndpointExceptionCount, brokenEndpointExpectedCount);
}
return result;
}
编辑
一个假设可能是由于异步代码,Pex 遇到了一些问题。我检查了每一次运行,甚至伪造了主机的启动方法。没有异步方法。在某些情况下,我确实创建了 1 个任务,但我同步运行它(下面的证明)
Task endpointTask = endpoint.Start(innerCancellationToken);
if (endpointTask == null)
{
// This endpoint is broken, for simplicity we raise an exception in the normal pipe
Task faultedTask = new Task(() =>
{
throw new InvalidOperationException("Endpoint returned a null valued task which is not allowed");
});
faultedTask.RunSynchronously();
innerTasks.Add(faultedTask);
break;
}
else
{
innerTasks.Add(endpointTask);
}
IHostEndpoint 存根是使用直接设置了值/状态的 TaskCompletionSource 创建的。
【问题讨论】:
-
System.NullReferenceException:对象引用未设置为对象的实例。 c:\users\koen\documents\visual studio 2010\Projects\ManagedHttp\ManagedHttp.Tests\HostTest.cs(98):在 System.Threading.Tasks.Task ManagedHttp.HostTest.Start(System.Threading.CancellationToken cancelToken, System .Int32 workingEndpoints, System.Int32 failedEndpoints, System.Int32 brokenEndpoints) 第 98 行是包含方法的右括号的行
-
您发布的代码中的哪一行对应>?
-
@ChrisF - 真的没有,只有在运行 pex 探索时才会引发此异常。一旦我调试该测试用例(右键单击失败的运行->调试),运行就会顺利成功。
-
另外值得补充的是,当我删除检查(及其内部块)时:if (failingEndpoints > 0 || brokenEndpoints > 0),没有异常发生
标签: c# .net moles pex pex-and-moles