Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TDD: Why is there only one test per function?

Tags:

oop

tdd

I'm having a hard time understanding why there is only one test per function in most professional TDD code that I have seen. When I approached TDD initially I tended to group 4-5 tests per function if they were related but I see that doesn't seem to be the standard. I know that it is more descriptive to have just one test per function because you can more easily narrow down what the problem is, but I find myself struggling to come up with function names to differentiate the different tests since many are so similar.

So my question is: Is it truly a bad practice to put multiple tests in one function and if so why? Is there a consensus out there? Thanks

Edit: Wow tons of great answers. I'm convinced. You need to really separate them all out. I went through some recent tests I had written and separated them all and lo and behold it was way more easier to read and helped my understand MUCH better what I was testing. Also by giving the tests their own long verbose names it gave me ideas like "Oh wait I didn't test this other thing", so all around I think it's the way to go.

Great Answers. Gonna be hard to pick a winner

like image 336
Matthew Stopa Avatar asked Dec 26 '09 01:12

Matthew Stopa


1 Answers

looks like you're asking "why there is only one assertion per test in most professional TDD code I have seen". That's probably to increase test isolation, as well as test coverage in presence of failures. That's certainly the reason why I made my TDD library (for PHP) that way. say you have

function testFoo()
{
    $this->assertEquals(1, foo(10));
    $this->assertEquals(2, foo(20));
    $this->assertEquals(3, foo(30));
}

If the first assert fails, you don't get to see what would happen with the other two. That doesn't exactly help pinpoint the problem: is this something specific to the inputs, or is it systemic?

like image 126
just somebody Avatar answered Jan 03 '23 18:01

just somebody