Miha Jakovac

Logo

.NET & DevOps Engineer | Cloud Specialist | Team Enabler

My name is Miha and I've been tinkering with computers for some time now. I remember getting Pentium 100 in the late '90s and that's how it all started.

Specialities:

31 January 2021

Test if the records exist in SQL database with QAToolKit

by Miha J.

In the previous post, we looked into how we can test for tables, views, and stored procedures in the SQL database. Now, let’s continue with QAToolKit Database library and test for specific records in a database.

First, we define rules and generate scripts. The below rule will generate an SQL script that will check if the record with the name myname exists in the table mytable:

var generator = new SqlServerTestGenerator(options =>
{
    options.AddDatabaseRecordExitsRule(new List<DatabaseRecordExistRule>()
    {
        new DatabaseRecordExistRule()
        {
            TableName = "mytable",
            ColumnName = "name",
            Operator = "=",
            Value = "myname"
        }
    });
}

To execute the script we create the runner and run it:

var runner = new SqlServerTestRunner(scripts, options =>
{
    options.AddSQLServerConnection("server=localhost;user=user;password=mypassword;Initial Catalog=myDatabase");
});

List<DatabaseTestResult> results = await runner.Run();

This is the results object we get:

[
  {
    "DatabaseResult": false,
    "Variable": "mytable",
    "Script": "IF EXISTS (SELECT * FROM [mytable] WHERE [name] = 'myname') BEGIN Select 1 END ELSE BEGIN Select 0 END;",
    "DatabaseTestType": "RecordExist",
    "DatabaseKind": "SQLServer"
  }
]

DatabaseResult is false, which means the script returned 0 - we did not find the record in a table mytable. Additionally the runner returns DatabaseTestType and DatabaseKind parameters.

Read more about the library here.

tags: c# - tool - qatoolkit - database - sql