我有大约 12 个针对不同场景的单元测试,我需要在这些测试中调用一个异步方法(有时在一个测试中多次调用)。当我执行“全部运行”时,其中 3 个总是会失败。如果我使用“运行选定的测试”一一运行它们,它们将通过。我得到的输出异常是这样的:
System.AppDomainUnloadedException: Attempted to access an unloaded AppDomain. This can happen if the test(s) started a thread but did not stop it. Make sure that all the threads started by the test(s) are stopped before completion.
我无法真正共享代码,因为它非常大而且我不知道从哪里开始,所以这里是示例:
[TestMethod]
public async Task SampleTest()
{
var someProvider = new SomeProvider();
var result = await someProvider.IsSomethingValid();
Assert.IsTrue(result == SomeProvider.Status.Valid);
NetworkController.Disable();
result = await someProvider.IsSomethingValid();
Assert.IsTrue(result == SomeProvider.Status.Valid);
NetworkController.Enable();
}
编辑:
其他两种失败的方法分别为 future 和过去设置时间。
[TestMethod]
public async Task SetTimeToFutureTest()
{
var someProvider = new SomeProvider();
var today = TimeProvider.UtcNow().Date;
var result = await someProvider.IsSomethingValid();
Assert.IsTrue(result == SomeProvider.Status.Valid);
TimeProvider.SetDateTime(today.AddYears(1));
var result2 = await someProvider.IsSomethingValid();
Assert.IsTrue(result2 == SomeProvider.Status.Expired);
}
TimeProvider 看起来像这样:
public static class TimeProvider
{
/// <summary> Normally this is a pass-through to DateTime.Now, but it can be overridden with SetDateTime( .. ) for testing or debugging.
/// </summary>
public static Func<DateTime> UtcNow = () => DateTime.UtcNow;
/// <summary> Set time to return when SystemTime.UtcNow() is called.
/// </summary>
public static void SetDateTime(DateTime newDateTime)
{
UtcNow = () => newDateTime;
}
public static void ResetDateTime()
{
UtcNow = () => DateTime.UtcNow;
}
}
编辑2:
[TestCleanup]
public void TestCleanup()
{
TimeProvider.ResetDateTime();
}
其他方法类似,我会模拟时间/日期变化等。
我尝试通过获取 .Result() 等来同步调用该方法,但它没有帮助。我在网上阅读了大量关于此的 Material ,但仍在挣扎。
有没有人遇到过同样的问题?任何提示将不胜感激。
最佳答案
我看不到你在用你的测试初始化或清理做什么,但可能是因为你的所有测试方法都试图异步运行,测试运行器不允许在执行清理之前完成所有任务。
当您运行所有测试时,相同的几种方法是否失败了还是随机的?你确定你在做单元测试而不是集成测试吗? “NetworkController”类给我的印象是您可能正在做更多的集成测试。如果是这种情况,并且您使用的是通用类、提供程序、服务或存储介质(数据库、文件系统),那么由一种方法引起的交互或状态更改可能会影响另一种测试方法的功效。
关于c# - 单元测试在全部运行时失败,但在单独运行时通过,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42263941/