I am currently trying to create unit tests for my method that is inserting data into my database. I know that I need to either mock or create a fake class so that my test data does not into added to my database, but I am not sure how to go about doing this. Does anyone have an idea?
Here is my code that my console "User Interface" touches. This is in my "Business" C# project:
/// <summary>
/// Gets the connection string.
/// </summary>
private static readonly string _connectionString = ConfigurationManager.ConnectionStrings["Database"].ConnectionString;
/// <summary>
/// Inserts a new admin into the Admins database table.
/// </summary>
/// <param name="admin">Admin record.</param>
public static void InsertNewAdmin(Admin admin)
{
var adminDatabaseWriter = new AdminDatabaseWriter(_connectionString);
adminDatabaseWriter.Insert(admin);
}
From there it goes into my AdminDatabaseWriter class and does the following in the method "Insert":
/// <summary>
/// Inserts a new admin into the Admins database table.
/// </summary>
/// <param name="admin">Admin record.</param>
public void Insert(Admin admin)
{
using SqlConnection sqlConnection = new(_connectionString);
sqlConnection.Open();
using SqlCommand sqlCommand = DatabaseHelper.CreateNewSqlCommandWithStoredProcedure("InsertNewAdmin", sqlConnection);
sqlCommand.Parameters.AddWithValue("@PIN", admin.PIN);
sqlCommand.Parameters.AddWithValue("@AdminType", admin.AdminTypeCode);
sqlCommand.Parameters.AddWithValue("@FirstName", admin.FirstName);
sqlCommand.Parameters.AddWithValue("@LastName", admin.LastName);
sqlCommand.Parameters.AddWithValue("@EmailAddress", admin.EmailAddress);
sqlCommand.Parameters.AddWithValue("@Password", admin.Password);
sqlCommand.Parameters.AddWithValue("@AssessmentScore", admin.AssessmentScore);
var userAddedSuccessfully = sqlCommand.ExecuteNonQuery();
sqlConnection.Close();
if (userAddedSuccessfully < 0)
{
throw new AdminNotAddedToDatabaseException("User was unsuccessful at being uploaded to the database for an unknown reason.");
}
}
Again, I am trying to unit test this last piece of code that I have attached. What would be the best way to test that my code actually added the object into the database without actually adding it to the database.