开发者

What are the best practices for unit testing properties with code in the setter?

I'm fairly new to unit testing and we are actually attempting to use it on a project. There is a property like this.

    public TimeSpan CountDown
    {
        get
        {
            return _countDown;
        }
        set
        {
            long fraction = value.Ticks % 10000000;
            value -= TimeSpan.FromTicks(fraction);
            if(fraction > 5000000)
                value += TimeSpan.FromSeconds(1);
            if(_countDown != value)
            {
            开发者_开发知识库    _countDown = value;
                NotifyChanged("CountDown");
            }
        }
    }

My test looks like this.

[TestMethod]
    public void CountDownTest_GetSet_PropChangedShouldFire()
    {
        ManualRafflePresenter target = new ManualRafflePresenter();
        bool fired = false;
        string name = null;
        target.PropertyChanged += new PropertyChangedEventHandler((o, a) =>
        {
            fired = true;
            name = a.PropertyName;
        });
        TimeSpan expected = new TimeSpan(0, 1, 25);
        TimeSpan actual;
        target.CountDown = expected;
        actual = target.CountDown;
        Assert.AreEqual(expected, actual);
        Assert.IsTrue(fired);
        Assert.AreEqual("CountDown", name);
    }

The question is how do I test the code in the setter? Do I break it out into a method? If I do it would probably be private since no one else needs to use this. But they say not to test private methods. Do make a class if this is the only case? would two uses of this code make a class worthwhile? What is wrong with this code from a design standpoint. What is correct?


The way you've got is fine (call the setter and then check the get returns the expected value).

Make sure you choose a selection of test values that exercise all the paths in that setter. A single set/get test isn't sufficient coverage.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜