Unit testing in D

August 21st, 2007 Leave a comment Go to comments

This code is partly described in the Agile low level programming with D-post.

import std.stdio;
import std.math;

struct Vector3 {
  real x, y, z;

  Vector3 opNeg() {
    return Vector3(-x, -y, -z);
  }

  Vector3 opAdd(Vector3 a) {
    return Vector3(x + a.x, y + a.y, z + a.z);
  }

  Vector3 opSub(Vector3 a) {
    return Vector3(x + a.x, y + a.y, z + a.z);
  }

  Vector3 opMul(real k) {
    return Vector3(x * k, y * k, z * k);
  }

  Vector3 opDiv(real k) {
    return Vector3(x / k, y / k, z / k);
  }

  Vector3 crossProduct(Vector3 a) {
    return Vector3(y*a.z - z*a.y, z*a.x - x*a.z, x*a.y - y*a.x);
  }

  real dotProduct(Vector3 a) {
    return x*a.x + y*a.y + z*a.z;
  }

  real length() {
    return sqrt(x*x + y*y + z*z);
  }

  unittest
  {
    void assertEqual(Vector3 desired, Vector3 actual, char[] msg) {
      assert(desired.x == actual.x, msg ~ ": x not equal");
      assert(desired.y == actual.y, msg ~ ": y not equal");
      assert(desired.z == actual.z, msg ~ ": z not equal");
    }

    // Test Fixture
    Vector3 v1 = Vector3(1, 2, 3);
    Vector3 v2 = Vector3(3, 2, 1);

    assertEqual(Vector3(4, 4, 4), v1 + v2,
      "Testing add operator");

    assertEqual(Vector3(4, 4, 4), v1 - v2,
      "Testing sub operator");

    assertEqual(Vector3(-1, -2, -3), -v1,
      "Testing neg operator");

    assertEqual(Vector3(2, 4, 6), v1 * 2,
      "Testing mul operator with scalar");

    assertEqual(Vector3(0.5, 1, 1.5), v1 / 2,
      "Testing div operator with scalar");

    assertEqual(Vector3(-4, 8, -4), v1.crossProduct(v2),
      "Testing cross product");

    assert(10 == v1.dotProduct(v2),
      "Testing dot product");

    assert(sqrt(14.0) == v1.length(),
      "Testing length");
  }
}

int main(char[][] args)
{
	writefln("All unit tests passed!");
	return 0;
}