In these days I’m trying to rewrite an old application using Mono.
I’m currently a newbie about Mono and the .Net world, but I happily noticed that the Mono environment come with a bundled interface to NUnit, so I can keep on writing tests as I’m slowly but steadily getting used to.
After having put together a bunch of classes and relative and unit tests, it was time to write the first integration test. I needed to put the development database in a known state before running the test, so I came up with the following class, that I’d like to share with you.
-
using System;
-
using System.Collections;
-
using NUnit.Framework;
-
using System.IO;
-
using System.Data;
-
using System.Data.SqlClient;
-
namespace TellItMailer{
-
public class TestDbSetup{
-
public void SetUpDbForTest(object test){
-
String path = test.GetType().FullName + ".sql";
-
path = path.Replace(this.GetType().Namespace + ".", "");
-
path = "/home/danidemi/workspace/TellItMailer/Tests/" + path;
-
//Read the script
-
String script = "";
-
using (StreamReader sr = File.OpenText(path)){
-
string s = "";
-
while ((s = sr.ReadLine()) != null){
-
script = script + s;
-
}
-
}
-
-
string connectionString =
-
"Server=192.168.75.128\\SQLEXPRESS;" +
-
"Database=TellIt_test;" +
-
"User ID=user;" +
-
"Password=password;";
-
-
IDbConnection dbcon;
-
using(dbcon = new SqlConnection(connectionString)){
-
dbcon.Open();
-
using (IDbCommand dbcmd = dbcon.CreateCommand()) {
-
dbcmd.CommandText = script;
-
dbcmd.ExecuteNonQuery();
-
}
-
}
-
}
-
-
}
-
}
It’s quite useful. Essentially this class loads a SQL script file whose name is the same of the test class, and execute it.
In this way you have for example a TestFeature.cs file alongside a TestFeature.sql file. Nice if your IDE shows files sorted alphabetically.
I found that the best place to use the class is inside the SetUp marked method. In this way the SQL script is run before each test. Doing it in a local development environment is not so bad, since the scripts are executed at high speed.
So, this is an example of how a test that uses TestDbSetup looks like.
-
using System;
-
using NUnit.Framework;
-
using log4net;
-
using log4net.Config;
-
namespace TellItMailer {
-
[TestFixture()]
-
public class IntegrationTest {
-
[SetUp]
-
public void SetUp(){
-
new TestDbSetup().SetUpDbForTest(this);
-
}
-
-
[Test]
-
public void TestCase(){
-
BasicConfigurator.Configure();
-
}
-
}
-
}
Pretty useful, IMHO.