rpeshkov
rpeshkov

Reputation: 5047

Simple or more complex tests?

Started learning TDD and met some misunderstandings about different approaches for writing tests.

In some articles it is said that you should write new test for every case. So, there can be two or more tests for a single method.

Another approach that I saw, is about writing more complex tests in several steps. For example: write test -> fail -> write code -> success -> modify current test (add new assertions) -> fail -> write code -> success -> and so on. After this steps done test is covering a whole logic of a single method.

What are pros and cons of that approaches of using TDD?

Upvotes: 1

Views: 107

Answers (1)

Andre
Andre

Reputation: 1607

It is "easier" to just add a bunch of assertions to an existing test case because you don't need to create new test cases (and come up with names for them), but I would prefer to write smaller tests that are more specific. The main advantage is that you will have better information if/when a test fails about what went wrong.

Let's see if I can come up with a contrived example:

[Fact]
public void TestEverything()
{
    var foo = new Foo();
    Assert.Equal(42, foo.TheAnswer);
    Assert.Equal(string.Empty, foo.Log);
    foo.DoSomething();
    Assert.Equal("something was done", foo.Log);
}


[Fact]
public void TheAnswer_AfterCreation_ShouldAdhereToTheHitchhikersGuide()
{
    var foo = new Foo();
    Assert.Equal(42, foo.TheAnswer);
}

[Fact]
public void Log_AfterCreation_ShouldBeEmpty()
{
    var foo = new Foo();
    Assert.Equal(string.Empty, foo.Log);
}

[Fact]
public void Log_DoSomething_ShouldLogSomething()
{
    var foo = new Foo();
    foo.DoSomething();
    Assert.Equal("something was done", foo.Log);
}

As you can see, inventing good names for test methods is really hard (and I did a bad job especially for the last one), but just imaging what happens if TheAnswer_AfterCreation_ShouldAdhereToTheHitchhikersGuide fails: you will get a pretty nice description from your test harness instead of the information that TestEverything has failed (Challenge: try to come up with a better name for it ;-) )

Upvotes: 4

Related Questions