Unit tests are automated tests written and run by software developers to ensure that a section of an application (known as the "unit") meets its design and behaves as intended.
I wanted to add unit tests to a Visual Basic Console App that fetched data from a database using SqlConnection, SqlCommand, SqlDataAdapter and DataTable classes.
In any case it is best practice is for Unit Tests to run independent of a running database server.
I created a new project (in a new solution)
I selected the .NET Framework (old school)
I selected .NET Framework 4.7.2
Main
I added Hello World code
I updated the Console Application to connect to a database and display the contents of a Tasks table
I added a second project to the solution. I selected the Unit Test Project (.NET Framework) template
I accepted the defaults
I added a reference to the Test project
I asked ChatGPT to generate unit tests for the code.
Write Unit Tests for this code
Imports System.Data.SqlClient
Module Module1
...
To write unit tests for the given code, you can use a testing framework such as NUnit or xUnit. However, since the code primarily consists of database interactions and console output, it may not be feasible to write traditional unit tests for it.
Instead, you can consider refactoring the code to improve testability by separating concerns. One approach could be to move the database-related code into a separate class or method that returns the result DataTable. Then, you can write unit tests specifically for that database-related code.
Here's an example of how you can refactor the code and write unit tests for the database interaction part using NUnit:
...
UnitTest1.vb
Database Tests
As ChatGPT explained it is hard to create Unit Tests for the database and Console code contained in the Module1.vb.
It does not help that the database access and Console.WriteLine code is mixed together in a single block.
I extracted the WriteDataTable code to create a function that was easier to create Unit Tests for.
I wrote the UnitTestProject2 tests with the help of ChatGPT.
The WriteDataTable function expects to be passed a DataTable.
Module1.vb
UnitTestProject1 - UnitTest1.vb
UnitTestProject2 - UnitTest1.vb
Running the Unit Tests