Solving the diamond kata with property-based testing series
- How to get started with Property-based Testing in C#
- Input generators in property-based tests with FsCheck
- First and Last line content
- Height equals Width
- Outside space symmetry
- Symmetry around the vertical axis
- Symmetry around the horizontal axis
- No padding for input letter row
- Letters order
All code samples are available on github
Intro
Last time, we discovered some interesting patterns with the first and last line of the diamond. Today, we'll look more globally at the diamond's shape and figure out if there's a property hidden that we could exploit.
Height equals the width
If you look closely at any possible diamond, you'll find that the diamond is quadratic or, in other words, the height is always equal to the width. We cannot see it here because of the font I use on my blog, but if you look at the number of char per line, you'll realize that it's equal to the number of lines.
e.g.
input: E
<---9--->
----A---- ^
---B-B--- |
--C---C-- |
-D-----D- |
E-------E 9
-D-----D- |
--C---C-- |
---B-B--- |
----A---- v
C# Tests
[Property(Arbitrary = new[] { typeof(LetterGenerator) })]
public Property DiamondWidthEqualsHeight(char c)
{
var diamondLines = Diamond.Generate(c).ToList();
return diamondLines.All(row => row.Length == diamondLines.Count).ToProperty();
}
Here we used some built-in methods of the .NET library, which makes these tests simple to read and short to write. It almost reads like a sentence.
Diamond.Generate(c)
Generates the diamondAll()
validates the inner condition for each linerow => row.Length == diamondLines.Count
validates that the number of letter per row is equal to the number of rows in the diamondToProperty()
Transforms a boolean expression to a property
If you are wondering what's
[Property(Arbitrary = new[] { typeof(LetterGenerator) })]
it's probably because you missed my previous post
Wrapping up
So far, we have three useful tests that are reducing the scope of possible errors in our implementation of the DiamondGenerator. However, there's still some way to go before we can call it a complete suite of tests and be confident that our code is unbreakable.
Solving the diamond kata with property-based testing series
- How to get started with Property-based Testing in C#
- Input generators in property-based tests with FsCheck
- First and Last line content
- Height equals Width
- Outside space symmetry
- Symmetry around the vertical axis
- Symmetry around the horizontal axis
- No padding for input letter row
- Letters order
All code samples are available on github