0

Do you think that this is a good way for testing exceptions and throwing? Any suggestions?

This are my code witch I wold like to test the exception:

 public void  EstablishConnection(string user, string pass)
        {
                 try{

                string connstring = String.Format("Server=" + CONNECTION_HOST + ";Port=" + CONNECTION_PORT + ";Database=" + CONNECTION_DATABASE + ";User Id=" + user + ";Password='" + pass + "';" + CONNECTION_OPTIONS);
                connection = new NpgsqlConnection(connstring);
                connection.Open();

                if (connection.State != ConnectionState.Open)
                {
                                IsConnected = false;
                }
                IsConnected = true;

            }catch (Exception e)
            {
                throw;
            }
        }

Unit testing code that I used for testing:

   [TestMethod]
        [ExpectedException(typeof(ArgumentNullException))]
        public void EstablishEndGetConnectionTest()
        {
            DbRepository core = null;

             core = DbRepository.GetInstance();
             core.EstablishConnection("postgres", "1234");
             Assert.IsTrue(core.IsConnected);

        }
user3223293
  • 83
  • 2
  • 11
  • Similar question: http://stackoverflow.com/questions/933613/how-do-i-use-assert-to-verify-that-an-exception-has-been-thrown – Ulric Sep 11 '15 at 09:27

1 Answers1

1

You're catching all exceptions and are currently re-throwing them directly. So basically your try/catch block is useless.

try
{
}
catch (Exception e)
{
    // Unless you do something here, the try/catch block is useless
    throw;
}

Second point, you should not expect the exception ArgumentNullException to be thrown; you should always check for null values before calling methods.

As for the [ExpectedException] attribute itself, it's fine.

ken2k
  • 48,145
  • 10
  • 116
  • 176