2

私はいくつかの N ユニット テストを書いていますが、少し問題があります。コード内でTest を に接続しようとしてTestCaseSourceいますが、オブジェクトが正しく構築されていないようです。

これが私のテスト方法です:

    [Test, TestCaseSource(typeof(TestCaseStuff), "GetTestCases", Category = "Release")]
    public void WithdrawMoney(TestCaseStuff tc)
    {
        double newBalance = AccountBalance - tc.amt;
        if (newBalance < 0)
        {
            Assert.Fail(String.Format("You can't withdraw {0}! You've maxed" +
                "out your bank account.", tc.amt.ToString("C2")));
        }

        AccountBalance = newBalance;
        Assert.Pass(String.Format("Your new balance is {0}.", 
        (AccountBalance).ToString("C2")));
    }

そして私のTestCaseSource

public class TestCaseStuff
{
    public double amt { get; set; }

    public TestCaseStuff()
    {
        Random rnd = new Random();
        this.amt = rnd.Next(0, 20);
    }

    [Category("Release")]
    public IEnumerable<TestCaseData> GetTestCases()
    {
        for (int i = 0; i < 500; i++)
        {
            yield return new TestCaseData(this);
        }
    }
}

これは主に概念実証として機能するため、複雑なオブジェクトを使用して実際のテストを作成するときに、上記のようなループを作成してオブジェクトにランダムな値を入れるだけでよいことがわかります。ただし、TestCaseStuffテスト メソッドに返されるすべてのインスタンスは同じです。

アップデート:

下の答えは正しいです。それを N-UnitsTestCaseDataオブジェクトに渡すとき、(誤って) そのインスタンスを単に値渡しすると想定していました。どうやら、それは参照によって行われるため、値は常に同じでした。

その上、Randomクラスを間違って使用していました。普段は扱っていないのですが、ちゃんと読み込めませんでした。以下のリンクで説明されているように、Randomデフォルトのコンストラクターで使用する場合、シード値はシステム クロックから派生します。その結果、複数のRandomオブジェクトを立て続けにインスタンス化すると、それらは同じデフォルトのシード値を共有し、同じ値を生成します。

したがって、これらの開発の結果、私のコードは次のようになります。

public class TestCaseStuff
{
    public double amt { get; set; }
    private static readonly Random rnd = new Random();

    public TestCaseStuff()
    {
        this.amt = rnd.Next(0, 20);
    }

    [Category("Release")]
    public IEnumerable<TestCaseData> GetTestCases()
    {
        for (int i = 0; i < 500; i++)
        {
            yield return new TestCaseData(new TestCaseStuff());
        }
    }

}
4

2 に答える 2

3

上記のコードは、の1つのコピーのみをインスタンス化TestCaseSourceし、同じ値をフィードし続けます。

すべてのループで乱数を生成する場合は、オブジェクトの静的インスタンスを作成し、新しいオブジェクトRandomを作成するたびにそこから乱数を生成する必要があると思います。TestCaseStuff

TestCaseStuffを次のように書き直します。

public class TestCaseStuff
{
    // Static instance of a random number generator.
    private static readonly Random RNG = new Random();

    public double amt { get; set; }

    public TestCaseStuff()
    {
        this.amt = RNG.Next(0, 20);
    }

    [Category("Release")]
    public IEnumerable<TestCaseData> GetTestCases()
    {
        for (int i = 0; i < 500; i++)
        {
            // NOTE: You need to create a new instance here.
            yield return new TestCaseData(new TestCaseStuff());
        }
    }
}
于 2012-10-10T15:03:13.220 に答える