Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit testing if a method is creating a record in Database

Just started learning and writing unit testing a day ago so this is probably too simple question:

I have this method in my DBTaskHanlder class that I want to do some unit for, I was able to write one for when ModelState is not valid but now for next one:

public bool CreateTask(ForgotPasswordViewModel fpModel)
{
    if (!ModelState.IsValid)
    {
        return false;
    }

    try
    {
         CreateTaskFromModel(fpModel);
        _dbContext.SaveChanges();
        return true;
    }
    catch (Exception e)
    {
        var issue = e.ToString();
        throw;
    }
}

That CreateTaskFromModel is a private method and well called its job is to create a new row in database on a table. So I wanted to test when this method is called is one new row getting created in DB? Is it actually the correct thing to test? How to test ? I don't think we should hit and insert into the real database right?

   private void CreateTaskFromModel(ForgotPasswordViewModel fpModel)
    {
        var message = _dbContext.Create<Message>();          
        message.MessageType = "TASK".PadLeft(10);
        message.Assigned_User_K = fpModel.SendPasswordRequestTo.Trim();
        message.Assigned_Date = DateTime.Today;
        message.Source_User_K = string.Empty;
        message.Target_File_K = "WEBCFGPHRM";           
        message.Owner_User_K = string.Empty;
        message.Message_K = _keyGenerator.Get10ByteBase36Key();

        _dbContext.Messages.Add(message);
    }

1 Answers

I don't think we should hit and insert into the real database right?

Yes you should. It isn't a "unit test", but it is a valuable test. As you get better at programming, you'll find that most of your bugs are at the edges of your program where it touches other things like databases.

I like writing CRUD tests. One "test method" that actually performs a series of tests. Usually in this pattern:

  1. Create
  2. Read by primary key. Were all the fields properly set?
  3. Read by a collection. You'll get lots of records, is the newly created record in the collection?
  4. Update
  5. Read by primary key. Did the fields change correctly?
  6. Delete
  7. Read by primary key. Nothing was returned, right?
  8. Read by a collection. You'll get lots of records, is the newly created record no longer in the collection? Are the rest of the records still there?

Even though everything is in one big method, treat each step as its own test that happens to use the previous test as a setup.

like image 54
Jonathan Allen Avatar answered Dec 08 '25 22:12

Jonathan Allen