簡體   English   中英

在Try..Catch斷言中被捕獲

[英]Assert in Try..Catch block is caught

剛遇到一些有趣的行為- AssertCatchCatch

List<Decimal> consArray = new List<decimal>();
try
{
    Decimal d;
    Assert.IsTrue(Decimal.TryParse(item.Value, out d));
    consArray.Add(d);
}
catch (Exception e)
{
     Console.WriteLine(item.Value);
     Console.WriteLine(e);
}

Assert拋出AssertFailedException並被catch 一直認為,如果Assert失敗,則測試將失敗,並且連續執行將中止。 但在那種情況下-測試會繼續進行。 如果以后沒有發生任何錯誤-我會通過綠色測試! 從理論上講-這是正確的行為嗎?

編輯:我知道也許是.NET限制以及MsTest中如何進行斷言。 斷言引發異常。 由於catch捕獲其捕獲的所有內容,因此會斷言斷言異常。 但是理論上正確還是MsTest特定?

正如已經回答的那樣,這是正確的行為。 你可以改變你的代碼通過捕捉AssertFailedException並重新把它扔得到預期的行為。

        List<Decimal> consArray = new List<decimal>();
        try
        {
            Decimal d;
            Assert.IsTrue(Decimal.TryParse(item.Value, out d));
            consArray.Add(d);
        }
        catch (AssertFailedException)
        {
            throw;
        }

        catch (Exception e)
        {
            Console.WriteLine(item.Value);
            Console.WriteLine(e);
        }

您的代碼按預期工作。 Assert失敗時,將引發從Exception繼承的AssertFailedException 因此,您可以添加一個try-catch並捕獲它。

在你的情況下,添加一個throw在年底catch並重新拋出異常。

NUnit會做完全相同的事情。 就像我認為的任何其他測試框架一樣,但是我只知道C#中的MStestNUnit

我希望您的測試代碼不會包含Decimal.TryParse ,但是您的業務邏輯會做到這一點,您將使用對象和方法調用進行測試。

就像是:

var sut = new Sut();
var d = sut.DoSomethingThatReturnsTheDecimal(item.Value);

Assert.AreEqual(0.123, d, string.Format("passed value can not be parsed to decimal ({0})", item.Value);

為了更接近您的實現:

List<Decimal> consArray = new List<decimal>();

Decimal d = Decimal.MinValue;

// You don't need to try-catch a Decimal.TryParse
// Decimal.TryParse(item.Value, out d));

try
{
    d = Decimal.Parse(item.Value)
}
catch
{
    // Handle exception
}

Assert.AreEqual(0.123, d);

// Does the list add anything at all? In this sample it seems a bit redundant
consArray.Add(d);

無論如何,回答您的問題。 try-catch應該捕獲您的AssertFailedException

PS:捕獲AsserFailedException並將其重新拋出也可以,但是對我來說有點奇怪。 我努力將Assert s保留在任何try-catch塊之外。 但這可能只是我的意見,您並沒有要求:)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM