Unit Testing Mathematical Code

I am writing a small utility for calculating a complex mathematical formula (using the commons-math library for integration and finding roots). I tried to write it just like a regular business application, but I found that I was getting a rapidly growing number of classes. To get the first step of the calculations (a 1-line formula with two integrals), I already wrote 3 classes for each tiny bit of calculation so that I could use dependency injection and correctly mock all commons-math calls. It seems to get out of hand, but in the end I will have 20 classes for a problem that can be solved on 2 screens in one class (without unit testing). What would be your preferred approach? I am very inclined to rely only on acceptance and higher level tests for this.

+7
java math unit-testing testing
source share
2 answers

Do not allow testing to create completely unsuitable and incomprehensible code. And don't do the add-in with an object-oriented approach.

You are testing a function, i.e. idle, that produces the same result for the same arguments. And I think that how you should test it: give it arguments from all possible equivalence classes and approve the result.

+8
source share

In my experience, you should use Unit-Testing as a health check and a possible regression check. Of course, unit testing should be as thorough as possible, but sometimes it is very tiring to fully test the full functionality of the code.

Unit tests are not formal evidence. They cannot and will not force future errors and problems with your code. Check out common code use cases. If you need more reliability, then you need to create a large repository of regression tests. Fortunately, for common problems, there are several online databases for these kinds of things. TPLP , for example, is a database of problems (and solutions) for theoretical evidence.

One method that sometimes works for me ... usually in mathematical code, there are "simple but slow" methods and "fast but hard to program" methods. When writing code, you want to use fast but difficult to write (so you expect errors). So ... make a quick way to test the system (SUT). When you create Unit Test, create 1000 random problems and solve them using the simple but slow method. Then run SUT and make sure the answers are the same.

Assuming, of course, that creating random problems is an easy task to solve. Sometimes it is, sometimes it is not. It is difficult to say if you do not tell us about the mathematical code itself. Now ... Does this turn out ALL cases? Not. But he will receive "general" cases. And if in practice a corner case appears, wrap it in Unit Test and correct it in the next version of your code.

+4
source share

All Articles