Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TDD for a random algorithm

I've got a problem with tests. There is an algorithm for some fancy procedure. This algorithm takes a random number from a range [-999,999; +999,999], treats it like an id number from a table and performs some random operations in the database. This means that I need to call the method huge number of times to be sure that the random number distribution is correct.

I wanted to make all the code using TDD (just to learn it a little bit more).

The problem is that I don't know how to test the algorithm with TDD principle in mind.

According to TDD, no code should be run without writing a test first.

One of the solutions I think of is to have a dummy method in the main class called debug(text). This method will do nothing in the production code. However then I'd make a subclass with this method being overloaded and this time it would store some interesting information. This information could be later used by test to find out if the function works properly. The database connection will be mocked and will do nothing.

Another solution would be to create a mocked database connection which would store the interesting information, used later in tests. However it would be so huge amount of work to create such a connection that I don't think is worth spending time on it.

There will be integration tests later to check if the database is changed properly. But integration tests are not part of TDD.

Have I got into a place where TDD fails and is useless or too hard to use?

like image 695
Szymon Lipiński Avatar asked Mar 17 '26 01:03

Szymon Lipiński


1 Answers

Is it your random number function?

It is: The random number generator should be tested outside of anything that uses it.

It isn't: You shouldn't be testing it at all, unless you really have a need to validate how random it is. IMO not a great ROI, but it depends entirely on your actual needs.

The DB functionality should assume the RNG is actually R, and should be tested separately from the RNG–during testing you may not want to use the RNG. At the least, you may want to seed the RNG to make the tests repeatable–this may make correctness more difficult to verify.

like image 172
Dave Newton Avatar answered Mar 18 '26 13:03

Dave Newton