Pex在探索时会引发NullReferenceException
本文关键字:NullReferenceException 探索 Pex | 更新日期: 2023-09-27 18:30:49
我正在用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 创建的,并直接设置了值/状态。
Pex是一个很棒的工具,但它有错误。从您的陈述中,我可以看出这是 Pex 中的一个错误:添加断言不应导致不相关的 NullRef。我建议您在Pex论坛上报告此事。