is there a MsTest Equivalent of Assert.Warning in MbUnit ?
4 回答
最接近的匹配是Assert.Inconclusive()
- 它不会使测试失败,但也不会成功。它属于第三个阶段,称为不确定性。
单个 Inconclusive 测试将导致整个测试套件是 Inconclusive。
也有支持自定义消息的重载:
Assert.Inconclusive("Ploeh");
当我在某些项目中使用 NUnit 时,我遇到了类似的问题。尝试使用
Console.Write("Some Warning");
您可能想要使用自定义异常。
Assert.Inconclusive 的问题在于测试资源管理器声明测试甚至没有运行。这可能会在将来运行测试时产生误导,特别是如果测试由其他开发人员运行:
我喜欢的方式如下。首先,定义一个自定义UnitTestWarningException
. 我给了我一个额外的构造函数,所以我可以通过参数传递我的警告消息 String.Format-style:
public class UnitTestWarningException : Exception
{
public UnitTestWarningException(string Message) : base(Message) { }
public UnitTestWarningException(string Format, params object[] Args) : base(string.Format(Format, Args)) { }
}
然后,在您想以警告结束单元测试时,UnitTestWarningException
改为抛出:
[TestMethod]
public void TestMethod1()
{
.
.
.
try
{
WorkflowInvoker.Invoke(workflow1, inputDictionary);
}
catch (SqlException ex)
{
if (ex.Errors.Count > 0
&& ex.Errors[0].Procedure == "proc_AVAILABLEPLACEMENTNOTIFICATIONInsert")
{
//Likely to occur if we try to repeat an insert during development/debugging.
//Probably not interested--the mail has already been sent if we got as far as that proc.
throw new UnitTestWarningException("Note: after sending the mail, proc_AVAILABLEPLACEMENTNOTIFICATIONInsert threw an exception. This may be expected depending on test conditions. The exception was: {0}", ex.Message);
}
}
}
结果:测试资源管理器然后显示测试已执行,但失败并UnitTestWarningException
显示您的警告:
这是我关于如何使用nunit发出警告的技巧(我知道这个问题是关于 mstest 的,但这也应该有效)。与往常一样,我对任何改进都很感兴趣。这种方法对我有用。
背景:我有代码可以检查测试本身是否有正确的注释,并且有逻辑来检测是否有人在不更改注释的情况下复制并粘贴了另一个测试。这些是我想在没有正常 Assert.Inconclusive 阻止实际测试运行的情况下向开发人员显示的警告。有些专注于测试,清理重构阶段是删除警告。
任务:在所有其他断言运行后发出警告。这意味着甚至在 Assert.Fail 之后显示警告,这些警告通常发生在开发期间的测试中。
实现:(最好为所有测试文件创建一个基类):
public class BaseTestClass
{
public static StringBuilder Warnings;
[SetUp]
public virtual void Test_SetUp()
{
Warnings = new StringBuilder();
}
[TearDown]
public virtual void Test_TearDown()
{
if (Warnings.Length > 0)
{
string warningMessage = Warnings.ToString();
//-- cleared if there is more than one test running in the session
Warnings = new StringBuilder();
if (TestContext.CurrentContext.Result.Status == TestStatus.Failed)
{
Assert.Fail(warningMessage);
}
else
{
Assert.Inconclusive(warningMessage);
}
}
}
测试使用
[Test]
public void Sample_Test()
{
if (condition) Warning.AppendLine("Developer warning");
Assert.Fail("This Test Failed!");
}
实际结果:
"This Test Failed!"
"Developer warning"
测试状态失败 - 红色
如果测试通过并出现警告,您将获得 Inconclusive - YELLOW 状态。