TDD Best Practices for Complex Objects

I am trying to become more familiar with test-based development. So far I have seen some simple examples, but I still have problems approaching complex logic, for example, for example, this method in my DAL:

public static void UpdateUser(User user)
        {
            SqlConnection conn = new SqlConnection(ConfigurationSettings.AppSettings["WebSolutionConnectionString"]);
            SqlCommand cmd = new SqlCommand("WS_UpdateUser", conn);

            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add("@UserID", SqlDbType.Int, 4);
            cmd.Parameters.Add("@Alias", SqlDbType.NVarChar, 100);
            cmd.Parameters.Add("@Email", SqlDbType.NVarChar, 100);
            cmd.Parameters.Add("@Password", SqlDbType.NVarChar, 50);
            cmd.Parameters.Add("@Avatar", SqlDbType.NVarChar, 50);
            cmd.Parameters[0].Value = user.UserID;
            cmd.Parameters[1].Value = user.Alias;
            cmd.Parameters[2].Value = user.Email;
            cmd.Parameters[3].Value = user.Password;
            if (user.Avatar == string.Empty)
                cmd.Parameters[4].Value = System.DBNull.Value;
            else
                cmd.Parameters[4].Value = user.Avatar;

            conn.Open();
            cmd.ExecuteNonQuery();
            conn.Close();
        }

What would be good TDD methods for this method?

+3
source share
2 answers

Given that the code has already been written, let's talk about what makes testing difficult. The main problem here is that this method is a purely side effect: it does not return anything (void), and its effect is not observed in your code, on object land - the observed side effect should be that somewhere in the database data far, record is now updated.

" , , ", , , , , ( , ), - ( ) unit test , (2 , " " 2 ).

, , " TDD".

, 2 :

1) . , , , . , TDD, BDD, . , " " ( ), , . , , , - DAL , CreateUser, UpdateUser, ReadUser, , , - ", , , , , " - , , DAL , , .

* grab a connection
* create the parameters and types of the command
* fill in the parameters of the command from the object
* execute the command and clean up

: - . - :

public class UpdateUserCommandBuilder
{
   IConnectionConfiguration config;

   public void BuildAndExecute(User user)
   {
      var command = BuildCommand(user);
      ExecuteCommand(command);
   }

   public SqlCommand BuildCommand(User user)
   {
      var connection = config.GetConnection(); // so that you can mock it
      var command = new SqlCommand(...)

      command = CreateArguments(command); // you can verify that method now
      command = FillArguments(command, user); // and this one too

      return command;
   }
}

, , . : , . , , , , ! , , DAL, .

, !

+6

:

public static void UpdateUser ( , SqlConnection conn);

SQL. , AppSettings , , , . , , .

+1

All Articles