开发者

Unit Testing both sides of operation?

I'm just getting going with unit testing. Suppose I have a filter class to filter out boxes. Box and BoxFilter are defined like:

class Box
{
    double GetHeight()
    double GetWidth()
    double GetWeight()
}

class BoxFilter
{
    void SetMaxHeight()
    void SetMaxWidth()
    void SetMaxWeight()
    bool PassesFilter(Box box)
}

So if a box does not cross the various max thresholds, then it passes the filter.

My question is about writing unit tests for the BoxFilter class's PassesFilter method. I could create the BoxFilter in a SetUp() method and k开发者_如何学编程eep the BoxFilter settings constant and then manipulate the Box properties in each test to verify that it passes or fails. For example, set the max height, width, and weight to be 10 and then tweak the box properties to above or below 10 and assert the expected outcomes.

Or, I could keep the Box settings constant and manipulate the BoxFilter settings.

Or alternatively, I could test both scenarios: BoxFilter constant and changing Box, and Box constant and chaning BoxFilter.

Which is the correct way to unit test this method? Also would I want to test a range of values, not just say 10?


The idea behind unit testing is to cover both the code and the use cases. In general, you'd want to do this as simply and as completely as possible, in whatever way seems the most reasonable.

My (personal) preference would be to set up several BoxFilters with varying parameters to test filters with positive, zero, and negative parameters. For each BoxFilter, I'd test several different Boxes, also with positive, zero, and negative parameters, to be sure you've caught all of the invalid and edge cases. Then I'd create (at least) one BoxFilter with "normal" parameters and test various Boxes to be sure the correct ones pass the filter.

Kudos for thinking about unit testing early! I think you'll find that it makes development faster, easier, and just more pleasant.


I'd say it's just a matter of preference, because the way you change the values doesn't actually affect the logic you're testing. Every time you call PassesFilter(), only the current values of the box and the filter matter - how the values have changed in relation to the surrounding tests doesn't matter. If, on the other hand, you were testing code that actually deals with how sizes change over time, you should test both ways.

The most important thing is that you test corner cases - but whether you do this by testing a fixed filter of e.g. 8.0 vs. a box size of 7.99999, 8.0 and 8.00001 or the other way around shouldn't matter (personally, though, I'd go for a fixed filter and a varying box, since the common use case would presumably be to create a filter and then pass many boxes through it).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜