Unit Testing – Is This Method of Writing Unit Tests Correct?

cunit testing

I have created a small C# project to help me learn how to write good unit tests. I know that one important rule of unit testing is to test the smallest 'unit' of code possible so that if it fails you know exactly what part of the code needs to fixed. I need help with the following before I continue to implement more unit tests for the project:

If I have a Car class, for example, that creates a new Car object which has various attributes that are calculated when its' constructor method is called, would the two following tests be considered as overkill? Should there be one test that tests all calculated attributes of the Car object instead?

    [Test]
    public void CarEngineCalculatedValue()
    {
        BusinessObjects.Car car= new BusinessObjects.Car();
        Assert.GreaterOrEqual(car.Engine, 1);
    }

    [Test]
    public void CarNameCalculatedValue()
    {
        BusinessObjects.Car car= new BusinessObjects.Car();
        Assert.IsNotNull(car.Name);
    }

Should I have the above two test methods to test these things or should I have one test method that asserts the Car object has first been created and then test these things in the same test method?

Best Answer

To me, a unit test case (method) should test a single test scenario. This may require multiple asserts, and IMO this is fine. As both of your test methods are exercising the same scenario (creating an object and ensuring it is in a consistent initial state), I would merge them into a single test case.

As to how to discern what exactly failed out of multiple asserts, all the assert methods I can think of have overloads with an extra message parameter - use this wisely to provide clear failure messages.