2

我使用 NUnit 3.0运行测试。

我的问题是下一个:我有一个带有测试的类,并且在这个类的构造函数中有一个在所有测试之前运行的方法(因为它在构造函数中)。在执行此方法时,会发生错误,然后我使用CleanUp方法处理它。在CleanUp方法中,我使用TestContext.CurrentContext.Result.Outcome.Status属性来查看我运行的测试的状态。

问题是测试根本没有运行(因为前置条件方法失败)。那么为什么这个属性告诉我测试通过了呢?

这是我的一段代码:

public class DepositSuccessTests
{
        //attributes

        public DepositSuccessTests(string device, WayToPay merchant)
        {    
            SetUp();
            try
            {
                Deposit_Money(merchant); // this method invokes an exception
            }
            catch (Exception e)
            {
                CleanUp();
            }
        }

        [Test]
        //Test that I run but that is not executed because of exception in the constructor
        public void Check_Transaction_Merchant_In_Transactions()
        {
            _orderVerifications.CheckTransactionMerchantInTransactions_Back(_merchant);
        }

        [TearDown]
        public void CleanUp()
        {
            //In the next line my test result is "Passed"
            if (TestContext.CurrentContext.Result.Outcome.Status == TestStatus.Failed)
            {
                //Do something
            }
            _driver.Dispose();
        }
}
4

2 回答 2

2

即使该行Deposit_Money(merchant);引起了异常,您也已经捕获了它,因此就跑步者而言,没有问题,所有代码都已通过,没有错误。你知道有问题,我知道有问题,但跑步者没有。

如果您明确地在 catch 中失败,那么它会将其标记为未通过。

  try
  {
     Deposit_Money(merchant); // this method invokes an exception
  }
  catch (Exception e)
  {
      Assert.Fail(); /// Explicitly fail the test
      CleanUp();
  }
于 2016-01-26T12:57:49.707 回答
0

您需要允许在测试中抛出异常,严格来说,您的测试确实通过了。

删除测试中的错误检查,允许抛出异常,您应该会看到测试结果失败。

于 2016-01-26T12:59:17.750 回答