Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unit testing c# properties

Tags:

c#

.net

tdd

xunit

I am working with a class that has lots of properties. For example;

public class Bib
{        
    public int PartQty { get; set; }
}

Now to unit test; I did the xUnit test something like

    [Fact]
    public void CanGetAndSetPartQuantity()
    {
        const int expected = 3;

        var target = new Bib() {PartQty = expected};

        Assert.Equal(expected, target.PartQty);
    }

here, I hate how I am hard-coding expected = 3. What's a good way to test this property for accessor and mutator?

like image 969
socialMatrix Avatar asked May 03 '11 23:05

socialMatrix


2 Answers

Since this property has no behavior other than being a getter/setter for an integer, you're essentially just testing that the compiler worked. This adds basically no value to your test. Consider removing it entirely. That would alleviate you of this odd situation. :)

If you do have some behavior you're trying to capture (e.g., allowed boundary conditions) you only need to test those, and really nothing else. Usually you will have constants for those boundary conditions available as part of the object. Consider using those constants, +/- some appropriate increment.

like image 155
Robert P Avatar answered Oct 08 '22 18:10

Robert P


Constrained Non-determinism is a good fit for this kind of unit test. Write it like this instead:

[Fact]
public void CanGetAndSetPartQuantity()
{
    const int expected = new Random().Next();

    var target = new Bib() {PartQty = expected};

    Assert.Equal(expected, target.PartQty);
}

This ensures that the output correctly represents the input, no matter what the input is.

like image 43
Mark Seemann Avatar answered Oct 08 '22 18:10

Mark Seemann