Is it OK to have multiple assertions in a unit test when testing complex behavior?

后端 未结 3 1742
栀梦
栀梦 2021-01-17 04:06

Here is my specific scenario.

I have a class QueryQueue that wraps the QueryTask class within the ArcGIS API for Flex. This enables me to e

3条回答
  •  时光取名叫无心
    2021-01-17 04:44

    Let's focus on the tests you have identified first. All except the last one (mustReturnQueryQueueEventArgs...) are good ones and I could immediatelly tell what's being tested there (and that's very good sign, indicating they're descriptive and most likely simple).

    The only problem is your last test. Note that extensive use of words "and", "with", "or" in test name usually rings problems bell. It's not very clear what it's supposed to do. Return correct results comes to mind first, but one might argue it's vague term? This holds true, it is vague. However you'll often find out that this is indeed pretty common requirement, described in details by method/operation contract.

    In your particular case, I'd simplify last test to verify whether correct results are returned and that would be all. You tested states, events and stuff that lead to results building already, so there is no need to that again.

    Now, advices in links you provided are quite good ones actually, and generally, I suggest sticking to them (single assertion for one test). The question is, what single assertion really stands for? 1 line of code at the end of test? Let's consider this simple example then:

    // a method which updates two fields of our custom entity, MyEntity
    public void Update(MyEntity entity)
    {
        entity.Name = "some name";
        entity.Value = "some value";
    }
    

    This method contract is to perform those 2 operations. By success, we understand entity to be correctly updated. If one of them for some reasons fails, method as a unit is considered to fail. You can see where this is going; you'll either have two assertions or write custom comparer purely for testing purposes.

    Don't be tricked by single assertion; it's not about lines of code or number of asserts (however, in majority of tests you'll write this will indeed map 1:1), but about asserting single unit (in the example above, update is considered to be an unit). And unit might be in reality multiple things that don't make any sense at all without eachother.

    And this is exactly what one of questions you linked quotes (by Roy Osherove):

    My guideline is usually that you test one logical CONCEPT per test. you can have multiple asserts on the same object. they will usually be the same concept being tested.

    It's all about concept/responsibility; not the number of asserts.

提交回复
热议问题