myermian
myermian

Reputation: 32515

How do you unit test an algorithm in C#?

I've ran into a situation I'm not sure how to test: algorithms. Specifically, I'm attempting to write the Adler32 method and create a unit test for it, but I hit a brick wall at this point.

My first attempt ended up being a shortened version of the same code I had in my method, which just seems very wrong to do. My next attempt was to have a table of input values with expected results, then compare the expected results to actual results... this seemed like a good idea until I realized that the only way I know how to populate this table would be by running the algorithm. So I'm pretty much stuck. How does one go about unit testing an algorithm without reusing the algorithm in the unit tests (directly or indirectly)?

Upvotes: 4

Views: 439

Answers (2)

Samuel Neff
Samuel Neff

Reputation: 74909

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

If you're implementing an algorithm that doesn't have readily available input/output data, then re-implement the algorithm another way, such as in Excel, and generate data you know to be accurate. We do this often with statistical calculations for reports where we can generate data easily in Excel.

Upvotes: 6

Martin Podval
Martin Podval

Reputation: 1117

If we would talk about unit testing, as you want to provide test for one method/class, you must supply input and verify results of your algorithm.

As your algorithm makes some calculation which you can not trust by default (it's the point of testing), you need to verify results according to constant values. E.g. you supply 5 and your method return 17. Which is either fine or not - your test pass or fail.

Where to get 17? Use paper and pencil, online calculation website, whatever way which you can trust.

Test, especially unit ones, must be simple and very light. You should not provide some alternative approach how to calculate results and verify them against those from production code. This approach brings you two different implementation which you would have to maintain, refactor etc.

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

Upvotes: 0

Related Questions