Use Ruby to Unit Test C#

posted @ Wednesday, January 5, 2005 11:25 PM

 

As I mentioned earlier I would be posting an entry showing how to test your .NET code with Ruby. John Lam recently posted an example using Python.NET to test a C# class so I though I would use his C# example to show how you would do this with Ruby. First off, you will need the Ruby/.NET Bridge which is available here. Here is the C# class that we will be testing:

 

using System;
namespace Calc
{
public class Calc
{
public int Add(int x, int y)
{
return x + y;
}
public int Divide(int x, int y)
{
return x / y;
}
}
}

Next, compile that with the following command line:

 

csc /target:library Calc.cs

This will generate a Calc.dll file which you can load in your Ruby code as follows:

require 'dotnet'
require 'test/unit'
loadLibrary 'Calc'

class CalcTest < Test::Unit::TestCase
def test_divide
calc = Calc.new()
assert_equal(2, calc.Divide(8, 4))
end
def test_add
calc = Calc.new()
assert_equal(5, calc.Add(2, 3))
end
end

Run your code by calling "Ruby calctest.rb". Your output should be as follows:

 

>ruby testcalc.rb
Loaded suite testcalc
Started
..
Finished in 0.101 seconds.

2 tests, 2 assertions, 0 failures, 0 errors
>Exit code: 0

The test suite automatically runs all instance methods that start with 'test'. That's it, we can easily add or change new test cases in Ruby to test our Calc class that was written in C#.