我正在用 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 创建的。