0

I am trying to incorporate BDD into the teams working practices to make interactions with Business Analysts more effective. I recently asked this question: Should I pass an ID number from the feature file?

Please see the code below:

public class Chestnut
{
    private Guid _id;

    public Customer (Guid id)
    {
       if (id == Guid.Empty)
                throw new ArgumentException();           
         _id = id;
    }
    //Chestnut methods go here.
}

How would I test this class if I was using Specflow (like in my other question)? I was thinking about creating two tests:

1) A Chestnut is created because a valid ID is passed. 2) A Chestnut is not created because an empty ID is passed.

I was thinking about doing the following:

1) Given an ID; Then create a Chestnut with a valid state

2) Given an empty ID Then a validation error is presented for ID

Note that I am not specifying the ID in the actual scenario - because it is an implementation detail.

Is this a "good" test or is there another way of approaching this? Should I even be creating a test for this?

w0051977
  • 7,139

2 Answers2

1

That constructor has behaviour, so testing it might be sensible. In particular: why is this code being written if not to make a test pass?

A test that just checks that an object was created is an extremely weak test. What useful properties does this exercise? Close to none, because other parts of the code that have to create a Chestnut will have to run that constructor anyway.

The test that construction should fail for empty IDs is more valuable, but this raises the question what the business value of this check is and why an ID can even be empty. If you can answer that (and give this test scenario a sensible name) then great, but otherwise test it anyway.

Note that these tests on levels of “constructors” and “IDs” are probably super low level implementation details, and don't encode any useful behaviour. Which business-level requirements are addressed by this behaviour? For such low-level details, a Gherkin-style scenario likely requires inappropriate amounts of effort. Those BDD-style tests should usually focus on higher-level behaviour and requirements. If you test this (and you should!) then a simpler unit testing framework will be much more appropriate.

amon
  • 135,795
0

Testing a constructor with behavior makes sense. If something is public and can be tested explicitly it should be tested explicitly.

I have to disagree with Amon, you don't want to test the constructor implicitly with other tests. My understanding is that you specifically don't want to test anything the component you are testing is depending on explicitly. Keyword "test isolation". (Not talking integration tests)

Anyways, you have an if statement in a function. It must be tested by a unit test. Constructor of function.