Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
    }
like image 210
user441521 Avatar asked Oct 15 '25 18:10

user441521


1 Answers

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.

like image 84
Sergey Kalinichenko Avatar answered Oct 17 '25 08:10

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!