質問

I have a method that resets the value of two inputs:

public void ResetLocation(ref ushort x, ref ushort y) {
    x = 0x7fff;
    y = 0x7fff;
}

For the unit test on this, I have created two TestMethods:

[TestMethod]
public void ResetLocation_GivenReferenceValues_ValueXShouldBeReset() {
    ushort x = -5;
    ushort y = 0;
    SomeController someController = new SomeController();

    someController.ResetLocation(ref x, ref y);

    Assert.AreEqual(0x7fff, x);
}

[TestMethod]
public void ResetLocation_GivenReferenceValues_ValueYShouldBeReset() {
    ushort x = 0;
    ushort y = -3;
    SomeController someController = new SomeController();

    someController.ResetLocation(ref x, ref y);

    Assert.AreEqual(0x7fff, y);
}

The information I've gleaned about "best practices" for unit testing so far is that each unit tests should only ever have one assertion. But in case like this, would it make more sense to test both x and y in the same test unit (two assertions in a single test)?

[TestMethod]
public void ResetLocation_GivenReferenceValues_BothValuesShouldBeReset() {
    ushort x = -5;
    ushort y = 3;
    SomeController someController = new SomeController();

    someController.ResetLocation(ref x, ref y);

    Assert.AreEqual(0x7fff, x);
    Assert.AreEqual(0x7fff, y);
}

Is it a Bad Thing to have two assertions in a unit test like this?

役に立ちましたか?

解決

I don't see it as a bad thing to add multiple assertions in a single unit test. The main thing to watch out for is to ensure that the test is still understandable and easy to maintain. In other words: Don't create a test that is so complex that it needs a test itself :-)

I even don't mind putting my assertion in a loop in cases where it makes sense to test your code using a range of input.

A variation on this is to leverage built in test framework functionality to rerun the test using different input. I have done this with nunit in the past See more here:http://nunit.org/index.php?p=parameterizedTests&r=2.5

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top