Saniya
Saniya

Reputation: 35

Testing A function

I need to write a unit test for a function. I have no idea about testing and the examples I have seen are more maths oriented so I can not understand how to write a test for this funtion. Can Anyone please help me write a unit test for this function:

public static void CreateUser(
    int userId, 
    string name, 
    System.DateTime createdAt, 
    string createdBy, 
    System.DateTime modifiedAt, 
    string modifiedBy, 
    string address, 
    string city, 
    string province, 
    string country, 
    string postcode, 
    string phone)
{
    try
    {
        using (UserDbContext _usermain = new UserDbContext())
        {
            User newuser = new User()
            {
                UserId = userId,
                Name = name,
                CreatedAt = createdAt,
                CreatedBy = createdBy,
                ModifiedBy = modifiedBy,
                ModifiedAt = modifiedAt,
                Address = address,
                City = city
            };
            _usermain.Users.Add(newuser);
            _usermain.SaveChanges();
        }
    }
    catch (Exception ex)
    {
        string error = string.Format("Error in Creating User", ex.Message);
        throw new Exception(error, ex);
    }
}

Upvotes: 1

Views: 89

Answers (1)

D Stanley
D Stanley

Reputation: 152566

Unit tests should be written to validate the behavior of a function. In your case, your function is taking in input and updating a database. Writing a unit test will be difficult since databases are very hard to mock. You essentially would need to figure out a way to mock the UserDbContext, pass inputs to the function, and verify that the database is updated properly.

I would suggest that a unit test is not appropriate for this function. Its sole purpose is to mutate an external environment that you cannot easily mock. Some changes that would make it easier to test are:

  • inject the context instead of creating a new one (so you can pass in a mock). That's probably more trouble than it's worth.
  • Making it two functions - one to create a User and one to take the User and insert it into the database. (In that case I would unit test the first method but not the second). If you already have a unit test for the User constructor then the separation and unit test are not needed.

As a side note, catching any exception and throwing a new generic exception does not add value. In fact it removes value since you lose or hide the following information:

  • The original stack trace
  • The error message
  • The type of exception.

All of these are buried in the InnerException when you throw a new exception. Just take out the try/catch block and let the original exception bubble up if you're not going to do anything with it.

Upvotes: 1

Related Questions