Unit Testing Matrices

A quick few pointers this week on writing unit tests for 4×4 matrices.  I’m building myself a vector math library, and using Test Driven Development to make it.  I only get about an hour on the way to work – and another hour on the way back – to work on it, so it’s moving along slowly.  I add to it every time I find a vector math function I need for my iPhone project that I haven’t implemented yet :).  Most recently I needed to implement inverse matrices.  Here’s some things that helped me write unit tests for them.

A matrix has an inverse if and only if the determinant of that matrix is zero.  A matrix that can’t be inverted is called a singular matrix.  An easy way to create a singular matrix is to set an entire row, or an entire column to all zeros

void testDeterminant_SingularMatrix_ReturnsZero(){
	Matrix4 matrix(0, 0, 74, 1,
			0, 435, 0, 1,
			345, 0, 34, 1,
			0, 0, 0, 0);
	float expectedDeterminant = 0;
	TS_ASSERT_DELTA(matrix.Determinant(), expectedDeterminant, 0.0001f);

There aren’t a great lot of matrices out there that have nice neat integer inverses either.  I managed to find one in a discussion (which has since hidden from me in my web history) about different ways to calculate determinants, I post it here for your stealing:

void testInverse_NonSingularMatrix_ReturnTrueAndInverseMatrix(){
 Matrix4 matrix(	1, 1, 0, 0,
			1, 1, 1, 0,
			0, 1, 1, 0,
			0, 0, 0, 1);
	Matrix4 expectedInverse(0, 1,-1, 0,
				1,-1, 1, 0,
				-1, 1, 0, 0,
				0, 0, 0, 1);
	Matrix4 result = Matrix4::Zero;
	TS_ASSERT_EQUALS(matrix.Inverse(result), true);
	TS_ASSERT(result == expectedInverse);

For other helpful hints regarding the creating and testing of matrices, check out the Euclidean Space page on Matrices for plenty of win.

P.S. I will migrate my blog to WordPress on my own site soon, which should clean up a lot of the code formatting issues.  For now, my apologies.

3 thoughts on “Unit Testing Matrices

  1. @Anonymous: This was part of a vector math library I put together for a project I was developing using Test Driven Development. There’s a few other objects that I created as well (Vectors, Quaternions etc.) but I didn’t come across any issues writing tests for those so I didn’t really think they were worth a mention

Leave a Reply

Your email address will not be published. Required fields are marked *