It is still very raw and will probably change a lot, but already offers some cool features.
In this post we have a commented example of using the AssertionComponent from the UnityTestTools from code.
If you’re beginning on TDD, you might be scared of developing for testability and might have a hard time writing your tests. Fear not, because with Unity Test Tools you can at least have a small part of the TDD benefits using the Assertion Component. You can even use without code at all!
But using it without coding gives us a heavy drawback. If you set an Assertion Component in the inspector, it won’t survive your object being turned into a prefab. This means that your prefab won’t retain the Assertion Component configuration. But even if it did, I would rather set everything in code so I can have better control on it.
The Assertion Component is a component you attach to your GameObjects like any other. Using its many Comparers you can set a reference value for some parameter of your object. When your object’s parameter differs from the reference, the Assertion Component will throw an exception (you’ll get an error message in the console).
You can, for example, use an Assertion Component in your player character and compare the player’s transform position with a limiting GameObject position. It will throw an exception if your player character is out of its bounds.
You can actually use it to assert that any public field remains in a reference range, and this reference can be a field in another object, or a constant.
My first use of this was to make sure my player character would never leave the rendering area. I set camera anchors to the corners and compared the character horizontal position with the anchor’s horizontal position (it’s a 2D game with horizontal movement only)
Let’s see an example use. I’ll heavily comment the code to make it easier to follow. Do read the comments! There’s two cases illustrated in this code: one is comparing against a constant value, and the other is comparing against a field in another GameObject (this case commented out).
As you see, there isn’t any secret to using it like this. Notice though, that since it is undocumented, it can change at anytime. Use with care.
As I mentioned in the comments, you can open the source file for your Comparer and the AssertionComponents to check out the enum values. If you have IntelliSense you can just see its values in the autocompletion.
Another alternative is to add an AssertionComponent to a GameObject and check its values.
I wrote this post because I couldn’t find any reference for this on the net. While this might sound very simple to veterans, most developers aren’t veterans.
Unit Testing with Unity Test Tools!