gpt4 book ai didi

c# - MSTest 单元测试自行通过,运行其他测试时失败

转载 作者:太空狗 更新时间:2023-10-29 21:07:14 25 4
gpt4 key购买 nike

我遇到了一些 MSTest 单元测试的问题,这些单元测试在我单独运行时通过,但在我运行整个单元测试类时失败。这些测试测试了一些代码 SLaks helped me with earlier ,他警告我我所做的不是线程安全的。但是,现在我的代码更复杂了,我不知道如何让它成为线程安全的。这是我拥有的:

public static class DLLConfig
{
private static string _domain;

public static string Domain
{
get
{
return _domain = AlwaysReadFromFile
? readCredentialFromFile(DOMAIN_TAG)
: _domain ?? readCredentialFromFile(DOMAIN_TAG);
}
}
}

我的测试很简单:

string expected = "the value I know exists in the file";
string actual = DLLConfig.Domain;
Assert.AreEqual(expected, actual);

当我自己运行这个测试时,它通过了。当我将它与测试类中的所有其他测试(对不同属性执行类似检查)一起运行时,actualnull 且测试失败。我注意到对于类型为自定义 Enum 类型的属性来说这不是问题;也许我在使用 Domain 属性时遇到了这个问题,因为它是一个 string?或者这可能是 MSTest 工作方式的多线程问题?

最佳答案

我怀疑其他测试正在修改 DLLConfig 类中的某些值,这会导致 getter 的结果发生变化。单元测试应始终从已知的初始状态运行,因此您应该在测试方法本身或在每次测试之前运行的标有 TestInitialize 属性的方法中进行设置。

关于c# - MSTest 单元测试自行通过,运行其他测试时失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2991612/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com