I’m currently writing a library of helper functions to produce some repetitive markup. I have a reference to the markup the functions should produce, but I’m curious about how I should go about unit testing this?
There are a lot of unit tests needed to get full coverage of the number of different variations of output from each function. Currently, I have a T4 template for each function which builds unit tests for every combination of inputs to that function.
Each unit test does a single assert against a string containing the reference markup. However, writing out these individual bits of markup by hand would take a long time so I wrote another small helper function which basically replicates the same logic I’m testing, but in a less flexible manner, to produce the expected string.
It occurs to me that this may not be the best idea? Or is this an OK approach to this kind of problem? What are the best practices surrounding this?
Example unit test
[TestMethod]
public void Function_P1_P2_P3()
{
string markup = HelperLib.MakeMarkup(P1, P2, P3);
Assert.AreEqual(this.MakeExpectedString(P1, P2, P3), markup);
}
1
What I might consider is decomposing the logic that generates the markup into smaller units, which you can test in more granular fashion. It really sounds like you’re describing more of a conceptual integration test — “here’s a scheme for generating big hunk of markup that I want to generate and I’m testing that it’s the same as this slightly different scheme for generating that big hunk of markup.”
What I’d suggest that you want to test with a unit test has more of a narrative like “I want to test that when I pass in x for P1, this specific thing happens.” Now doing that might involve decomposing. For instance, if I have a GenerateTable() method and a GenerateTableRow() method, and a GenerateTableCell() method, I might have a test that says “when I pass foo to GenerateTableCell() I get back <td>foo</td>
“. Then you have another method that assembles cells into rows and rows into tables and you’re testing at each growing layer of abstraction.
3
You could parse the generated mark-up and make sure that the structure/content matches what should result from the arguments that you passed in when you ran the method.
It seems like this could be used evaluate all the different variations somewhat programatically (depending on how much your markup changes for different arguments), but I’m betting it’ll be a bit more work than comparing strings. 😉