locked
Is it possible to detect if I'm in a unit test? RRS feed

  • Question

  • Hi,

    I have to create unit tests for some code which has the bad habit of catching every exception. I can't check for example for expected exceptions this way.

    I can't change this except that I may rethrow any exception in the case of a unit test. But when searching for a possibilty to check if I'm in a unit test, I didn't find anything. Is there a possibility?

    • Moved by Robert Breitenhofer Wednesday, August 31, 2011 1:56 PM English instead German (From:Visual Studio)
    Wednesday, August 31, 2011 1:20 PM

Answers

  • Hi,

    There is also a non-intrusive way of checking. Depending on the test framework you use, you could check if the Microsoft.VisualStudio.QualityTools.UnitTestFramework assembly (or NUnit.Framework) was loaded to the current application domain. While this method mostly does its job, it's not 100% fool-proof, as there still is a probability that the framework was loaded, but no tests were performed. Checking for a test framework only tells you if the application is currently run in a test environment, nothing more. But hey, this might be enough for you.

    Jon Skeet: Determine if code is running as part of a unit test
    http://stackoverflow.com/questions/3167617/determine-if-code-is-running-as-part-of-a-unit-test

    Marcel


    Monday, September 5, 2011 6:39 AM

All replies

  • Hi Joachim,

    While this is technically speaking doable (at least at a certain degree), why would you ever need to do this? - The whole purpose of writing unit tests is to ensure that you have propper written, sound classes that bring real value to your application, and not to hide and mask their bad design.

    Having said that, take a look at one possible implementation:

    public class Person {
     public string FirstName { get; set; }
     public string LastName { get; set; }
    
     public Person(string firstName, string lastName) {
     FirstName = firstName;
    
     if (String.IsNullOrEmpty(lastName)) {
      object[] attributes = new StackTrace().GetFrame(1).GetMethod().DeclaringType.GetCustomAttributes(typeof(TestClassAttribute), false);
      if(attributes != null && attributes.Length > 0)
      throw new ArgumentNullException();
     }
    
     LastName = lastName;
     }
    }
    

    So if you were to construct the Person class inside a method declared by a class that is decorated with the TestClassAttribute, you would get the expected exception, in all other cases you would not get any exception at all. So this test would succeede:

    [TestMethod]
    [ExpectedException(typeof(ArgumentNullException))]
    public void WhenLastNameIsNullThrowExceptionIfRunFromUnitTest() {
     Person person = new Person("John", null);
     Assert.Fail("Should have thrown ArgumentNullException.");
    }
    

    BUT: Please do reconsider your options. If you don't, you are entangling your design, introducing dependencies on using Microsoft.VisualStudio.TestTools.UnitTesting etc.

    Marcel

    Wednesday, August 31, 2011 2:34 PM
  • Hi

    Use exception class to throw custom exception

    1. Custom Exception

    ---------------------

    Public

    Class MyCustomException

     

    Inherits System.ApplicationException

     

    Public Sub New(ByVal message As String)

     

    MyBase.New(message)

     

    End Sub

    End

    Class

    2. TestMethod

    --------------

    DataSource("MySqlDataSource")> _

     

    Public Sub TestMethodTest()

     

    Try
     

     

    If (ExpectedRowCount <> ActuaRowCount) Then

     

    Dim e As New MyCustomException("Row Count mismatch")

     

    End If

     

    Catch ex As Exception

    Assert.AreEqual(ex.Message,

    "Row Count mismatch")

     

    End Try

     

    End Sub

    I hope this wil solve your issue


    Premkumar.D
    Saturday, September 3, 2011 7:39 AM
  • Hi,

    There is also a non-intrusive way of checking. Depending on the test framework you use, you could check if the Microsoft.VisualStudio.QualityTools.UnitTestFramework assembly (or NUnit.Framework) was loaded to the current application domain. While this method mostly does its job, it's not 100% fool-proof, as there still is a probability that the framework was loaded, but no tests were performed. Checking for a test framework only tells you if the application is currently run in a test environment, nothing more. But hey, this might be enough for you.

    Jon Skeet: Determine if code is running as part of a unit test
    http://stackoverflow.com/questions/3167617/determine-if-code-is-running-as-part-of-a-unit-test

    Marcel


    Monday, September 5, 2011 6:39 AM