C# Unit Testing – How and What to Test in a Method?

cnettestingunit testing

I am relatively new to unit testing and have a query about what/how I should be testing a certain method. For the following (psudo-c#) method I have created (not a real-life example) what would you test for?

Initially, my thoughts would be to test the output with variations on the dictionary of form fields, e.g. valid, invalid, missing values. However I also wonder how you would test to make sure the object values have been changed to the correct value and that the correct email message was attempted to be sent (obviously both services could/would be mocked).

I hope what I am asking makes sense, I appreciate this is a subjective question and the answers may be 'it depends' 😉

public bool ProcessInput(Dictionary<string, string> formFields, ObjService objService, EmailService emailService)
    {
        try
        {
                   // Get my object id
                   int objId;
                   if(!int.TryParse(formField["objId"], out objId)
                   {
                      return false;
                   }

                   // Update my object - would you validate the save against a DB or a mocked inmemory db?
                   var myObj = objService.Find(objId);
                   myObj.Name = formField["objName"];
                   objService.Save(myObj);

                   // Send an email - how would you test to make sure content, recipient, etc was correct? 
                   emailService.SendEmail(formField("email"), "Hello World");

                   return true;    
        }
        catch(Exception ex)
        {
        return false;
        }
    }

Best Answer

You are on the right track. You should be testing (at least) the following scenarios:

  1. invalid (non-integer) object ID: the method should return false and no changes should be made (i.e. no services called)
  2. unknown object ID: the method should probably behave similarly to case 1 (but currently it does not seem to handle that case)
  3. valid object ID, valid name in the form field: object should be saved to the object service, email should be sent
  4. valid object ID but missing name in the form field: similar to case 3???

Both ObjService and EmailService should be mocked in your tests, then you can verify that they are (not) called with the expected parameters.

Related Topic