Monday, July 27, 2009

Avoiding code execution when debugging or testing an application

It is common to have some code that is part of some workflow and you don’t want it to execute when you are testing. For example, if your code sends an e-mail to some users, you don’t want to crud your users mail box with e-mails originated from your tests. Unless you are testing if sending the e-mail works, you can do this to test the rest of your code:

        static void SendMail(string to, string subject, string body)

#if !DEBUG
           using(var message = new MailMessage())
               message.From = new MailAddress(SiteSettings.Settings.AdminMail);
               message.To.Add(new MailAddress(to));
               message.Subject = subject;
               message.Body = body;
               message.BodyEncoding = Encoding.UTF8;
               message.SubjectEncoding = Encoding.UTF8;

               var mailClient = new SmtpClient();

The #if !DEBUG pre-processor will ensure that the code is not compiled into the assembly so it does not gets executed. Just remember to set your build configuration to “Debug” on Visual Studio.

No comments:

Post a Comment