簡體   English   中英

將Assert.That(而不是Assume.That)與[Theory]一起使用是錯誤的嗎?

[英]Is it wrong to use Assert.That (rather than Assume.That) with a [Theory]?

interface IPoint
{
    int X { get; }
    int Y { get; }
}

static bool CoincidesWith(this IPoint self, IPoint other); // implementation unknown

我想編寫一個NUnit測試,以驗證我對CoincidesWith含義的假設:

self.CoincidesWith(other) ⇔( self.X = other.X )∧( self.Y = other.Y

以下是到目前為止我能提出的最簡潔的測試:

[Theory]
void CoincidesWith_Iff_CoordinatesAreEqual(IPoint self, IPoint other)
{
    bool coordinatesAreEqual = (self.X == other.X && self.Y == other.Y);
    Assert.That(self.CoincidesWith(other) == coordinatesAreEqual);
}

我的問題按重要性從高到低依次為:

  1. 使用[Theory] ,使用Assert.That代替Assume.That是否被認為是錯誤的或不良的風格? 文檔似乎建議后者應與[Theory]結合使用。
  2. 這種情況確實比[Test]更適合[Theory] [Test]嗎?

經過一番思考后,我得出的結論是我的上述解決方案沒有任何問題。

這種情況確實比[Test]更適合[Theory] [Test]嗎?

如果CoincidesWith方法的實現可用於檢查(例如,作為源代碼),或者至少有充分的文獻證明,則無需進行假設-我可以簡單地查找我需要知道的內容。 在這種情況下, [Test] (或xUnit.net稱測試為[Fact] )似乎更合適。

但是,由於我無法訪問CoincidesWith的實現,並且文檔不足,因此,我確實需要對該方法的一般工作作一些假設或[Theory]

使用[Theory] ,使用Assert.That代替Assume.That是否被認為是錯誤的或不良的風格?

否。它只是要使用的另一種工具,而且比Assert.ThatAssert.That

[Theory]的上下文中, Assume.That這似乎是對所提供的[Datapoints]施加附加約束的正確方法,同時驗證了實際假設(使用使它們超出Assume.That那些數據點)。 Assert.That

一個例子可以說明這一點。 讓我們嘗試為此假設編寫一個測試:

給定一個偶數整數a和一個奇數整數b ,它們的乘積a * b是偶數。

僅當滿足前提條件時,才測試a * b是否有意義。 如果a不是一個偶數整數,或者b不是一個奇數整數,則測試既不應成功也不應該失敗; 應該沒有定論。 而這正是Assume.That 。這有助於實現。 但是,實際測試留給Assert.That

[Theory]
void GivenAnEvenIntegerAndAnOddInteger_ProductIsAnEvenInteger(int a, int b)
{
    Assume.That(a.IsEven());
    Assume.That(b.IsOdd());
    // note: the type system already ensures that `a` and `b` are integers.
    int product = a * b;
    Assert.That(product.IsEven());
    // note: the theory doesn't require `product` to be an integer, so even
    // if the type system didn't already assert this, we would not test for it.
}

[Datapoints]
int[] integers = { 1, 2, 3, 4, 5, 6, 7 };

static bool IsEven(this int integer) { … }
static bool IsOdd(this int integer) { … }

暫無
暫無

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

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