Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you write tests for code that requires duplicating the code under test?

Tags:

unit-testing

I'm working on moving as much logic out of a custom control as possible so that it can be unit tested to reduce manual testing burden. I'm having trouble with situations where a method under test produces a complex result; writing a test case that calculates the result would involve writing what is essentially the code under test into the test itself.

For example, I have a GeometryGenerator class that creates a WPF geometry based on the properties of the class. In one configuration, a PathGeometry that consists of an ArcSegment is generated. I can calculate what the arc's properties should be based on the test parameters, but this calculation is identical to the code that I'm trying to test. This seems like it would make the test ineffective; if there's a bug in the calculation there will be a bug in the test, and if the calculation changes in the method it might have to change in the test.

What do I do about this situation? The only approach I've come up with is to hand-calculate the results of my test cases and hard-code these values into the tests. Is this an acceptable approach (it seems like what I'd have done if I were writing the tests before the implementation)?

like image 618
OwenP Avatar asked Jan 01 '26 06:01

OwenP


2 Answers

The only approach I've come up with is to hand-calculate the results of my test cases and hard-code these values into the tests. Is this an acceptable approach (it seems like what I'd have done if I were writing the tests before the implementation)?

Yes, this is typical. For the purpose of unit testing you have to assume that the formula you're using to calculate your results is correct. It's the software implementation that you're testing.

You precompute a few hand-calculated results to make sure you're not using the code under test to generate the test data (a very bad sin in unit testing). Just make sure you document your test cases so you know what the expected values represent and where they came from.

like image 132
Bill the Lizard Avatar answered Jan 04 '26 13:01

Bill the Lizard


Hand calculating and hard-coding are bad in production code, but essential to good unit tests.

You generally want to write one test for each "state" of the code. For example, I often write tests with positive input, negative input, and zero input to make sure the code is working as expected.

like image 38
Yes - that Jake. Avatar answered Jan 04 '26 13:01

Yes - that Jake.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!