How do you unit test the algorithm in C #?

I ran into a situation, I'm not sure how to test: algorithms. In particular, I am trying to write an Adler32 method and create a unit test for it, but at that moment I hit a brick wall.

My first attempt turned out to be a shortened version of the same code as in my method, which seems very wrong. My next attempt was to have a table of input values ​​with expected results and then compare the expected results with the actual results ... it seemed like a good idea until I realized that the only way I know how to populate this table is - this is to run the algorithm. So I'm almost stuck. How to go about an algorithm testing module without reusing the algorithm in unit tests (directly or indirectly)?

+4
source share
2 answers

Use the table of inputs and known outputs as described. You need to get results from another implementation of the same algorithm from a source that, as you know, is accurate.

If you are implementing an algorithm that does not have readily available I / O data, repeat the implementation of the algorithm in another way, for example, in Excel, and create data that you know is accurate. We often do this with statistical calculations for reports in which we can easily generate data in Excel.

+6
source

If we were talking about unit testing, since you want to provide a test for one method / class, you must provide input and check the results of your algorithm.

As your algorithm does some calculations that you cannot trust by default (this is a testing point), you need to check the results against constant values . For instance. you supply 5 and your method returns 17 . Which is either beautiful or not - your test pass or failure.

Where to get 17 ? Use paper and pencil, an online settlement site, no matter how you trust.

The test, especially a single one, should be simple and very easy . You should not offer an alternative approach to how to calculate the results and test them against those that produce the code. This approach brings you two different implementations that you will need to support, refactoring, etc.

Obviously, you can provide a table of inputs and expected outputs, not just 5 and 17 .

0
source

Source: https://habr.com/ru/post/1499517/


All Articles