I am new to Nunit framework, C# and dotnet. How to write a test case using Nunit for a db connection. I was not able to find any examples of nunit covering db connections. The test case has to cover checking connection and closing it.
namespace TestConnection
{
class Program
{
static void Main(string[] args)
{
Connection con = new Connection();
con.ConnectionString = "Server = ab1-vm.app.test.com ;Port = 6080;Database = MY_DB;Schema = SCHM;User id = admin;PWD = *****;level=3;logname=C:\\my_logs";
Command cmd = con.CreateCommand();
Encoding e1 = Encoding.Default;
con.Open();
cmd.Connection = con;
try
{
string query = "SELECT \"X\", \"Y\", 1 FROM MY_DB..DIM_CONTRACT Z LIMIT 50 ";
cmd.CommandText = query;
DataReader rdr = cmd.ExecuteReader();
while (rdr.HasRows)
{
rdr.Read();
System.Console.WriteLine(rdr.GetString(0));
System.Console.WriteLine(rdr.GetString(1));
System.Console.WriteLine(rdr.GetInt32(2));
}
rdr.Close();
con.Close();
}
catch (Exception e)
{
System.Console.WriteLine(e.Message);
}
}
}
}
CodePudding user response:
Calling an assert function NUnit.Framework.Assert.That(con.State == ConnectionState)
for con.Open()
and con.close()
namespace TestProject
{
[TestClass] //Test Framework
public class UnitTest1
{
Connection con = new Connection();
[TestMethod] //Test Case 1
public void TestOpenConnection()
{
con.ConnectionString = "Server = ab1-vm.app.test.com ;Port = 6080;Database = MY_DB;Schema = SCHM;User id = admin;PWD = *****;level=3;logname=C:\\my_logs";
con.Open();
NUnit.Framework.Assert.That(con.State == ConnectionState.Open);
}
[TestMethod] //Test Case 2
public void TestCloseConnection()
{
con.ConnectionString = "Server = ab1-vm.app.test.com ;Port = 6080;Database = MY_DB;Schema = SCHM;User id = admin;PWD = *****;level=3;logname=C:\\my_logs";
con.Open(); //open the connection
con.Close(); //close to test if the connection closes
NUnit.Framework.Assert.That(con.State == ConnectionState.Closed);
}
}
}