dpwulp94
dpwulp94

Reputation: 163

SqlConnection command throws no Exception on delete

I am working on Unit Tests and i made a test that tests the following method:

public void DeleteTransport(int id)

   {
       SqlConnection sqlConnection = new SqlConnection(SQL_CONN);
       try
       {
           sqlConnection.Open();
           SqlCommand dbCommand = sqlConnection.CreateCommand();
           dbCommand.CommandText = string.Format("DELETE FROM dbo.Transports WHERE ID={0}", id);
           SqlDataAdapter dap = new SqlDataAdapter(dbCommand);

           var ds = new DataSet("Transports");
           dap.Fill(ds);
       }
       finally
       {
           sqlConnection.Close();
       }
   }

In the Unit Test, I give a not existing id as parameter, but the method doesnt throws an SqlException.

How to throw an Exception if the id doesnt exists?

I am using:

Upvotes: 2

Views: 194

Answers (1)

Darren
Darren

Reputation: 70718

This wouldn't throw an exception, it would simply update 0 rows.

You could check how many rows were affected by using ExecuteNonQuery() and if they are equal to 0, you could throw an Exception (Which would be computionally expensive) but would achieve what you expect.

You could also rewrite the unit test to Assert that the rows affected is greater than 0.

Upvotes: 2

Related Questions