今天我们意识到一些测试会抛出异常,但所有测试都“通过”。事实上,异常文本显示为绿色。
这有意义吗?
如果未处理异常,是否有办法使测试失败(我知道大多数情况下都会发生这种情况)?
截图:
测试方法:
[TestMethod]
public void CommunicationCore_CommunicationController_ConnectRequestWellProcessed()
{
// Arrange
IUnityContainer container = new UnityContainer();
ICommonInitializer initializer = new CommonInitializer(container);
initializer.Initialize(); // register all types
DriveConnection connectionSettings = CreateFakeConnetionSettings(1);
Transaction transaction = null;
ICommunicationController controller = container.Resolve<ICommunicationController>();
object locker = new object();
// Act
controller.Connect(
connectionSettings,
result =>
{
transaction = result;
lock (locker)
{
Monitor.Pulse(locker);
}
});
// asyncronous communication wait for the process of the message
lock (locker)
{
Monitor.Wait(locker, 10000);
}
// Assert
bool connectSuccessfully = (transaction != null) && !transaction.Response.ErrorResult.ErrorDetected;
Assert.IsTrue(connectSuccessfully);
((IDisposable)controller).Dispose();
}
最佳答案
从您发布的调用堆栈中,我看到异常发生在单独的线程中。
似乎只有在测试方法的调用线程中抛出异常才会导致测试失败。考虑这个例子:
[TestMethod]
public void ThreadExceptionTest()
{
new Thread(() => { throw new Exception("Error in thread"); }).Start();
}
另请参阅此问题:how-to-handle-exceptions-raised-in-other-threads-when-unit-testing
关于c# - 为什么单元测试中未处理的异常不会导致使用 MSTest 失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21903711/