user441521
user441521

Reputation: 6998

unit testing a function that doesn't return a value

I'm playing around with TDD and unit testing in general. All the examples I've seen return values and that seems like the easiest case. However what if my function doesn't return a value?

For example let's say I have an Actor class and I need a way to increase it's "health". I made a unit test like below and then make the Actor class to satisfy it, but is this ok and common to do? I don't see many examples using properties in the unit test. Should I be thinking differently with this kind of stuff?

    [TestMethod]
    public void IncreaseHealth_PositiveValue_PositiveHealth()
    {
        Actor a = new Actor();

        int beforeHealth = a.Health;

        a.IncreaseHealth(5);

        int afterHealth = a.Health;

        Assert.AreEqual(beforeHealth + 5, afterHealth);
    }

Upvotes: 3

Views: 1376

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726599

This test is a good start. However, just like when testing value-returning methods, you should test border conditions on methods with side effects. In this case, you should also check that

  • Your method does not take negatives (or takes negatives, and works as expected)
  • When incrementing the health by some large value that overflows integer the result remains predictable (e.g. the health is capped at some value)
  • When decrementing the health by a value that is greater than the current health, the remaining health does not become negative (unless that is allowed)
  • When the health goes to zero, whatever other things that may be triggered should be triggered.

Although your use of a locally initialized object is fine, you could also put one on the unit test object, and initialize it in your [Setup] method.

Upvotes: 4

Related Questions