Unit testing and coding

In many TDD tutorials, I see code like this:

public class MyClass
{
    public void DoSomething(string Data)
    {
      if (String.IsNullOrWhiteSpace(Data))
        throw new NullReferenceException();
    }
}


[Test]
public DoSomething_NullParameter_ThrowsException()
{
   var logic = MyClass();

   Assert.Throws<NullReferenceException>(() => logic.DoSomething(null));
}

All this makes sense, but at some point you will end up in a class that actually uses MyClass, and you want to check if the exception is being processed:

public class EntryPointClass
{
  public void DoIt(string Data)
  {
     var logicClass = new MyClass();

     try
     {
        logicClass.DoSomething(Data);
     }
     catch(NullReferenceException ex)
     {

     }
  }
}

[Test]
public DoIt_NullParameter_IsHandled()
{
  var logic = new EntryPointClass()

  try
  {
    logic.DoIt(null);
  }
  catch
  {
    Assert.Fail();
  }
}

So, why not put try / catch in MyClass first and not throw an exception and test the null value in the MyClass unit test class, and not in the EntryPointClass unit test class?

+5
source share
5 answers

Typically, exception handling will look like this:

public class EntryPointClass
{
  Logger _logfile;
  // ...
  public void DoIt(string Data)
  {
     var logicClass = new MyClass();

     try
     {
        logicClass.DoSomething(Data);
     }
     catch(NullReferenceException ex)
     {
         _logfile.WriteLine("null reference exception occured in method 'DoIt'");
     }
  }
}

(Logger - , , , MyClass. - .)

MyClass ( , , , ).

, TDD. , MyClass , -, . , . , , unit test MyClass, MyClass .

, , EntryPointClass , - , . , , constrcution, ILogger, . , :

 public class EntryPointClass 
 {
      // ....
      catch(NullReferenceException ex)
      {
          if(_logfile!=null)
              _logfile.WriteLine("null reference exception occured in method 'DoIt'");
      }    
      // ....
 }
+3

(. MSDN ). null DoSomething, , , . , Exception Throwing, :

. , , , .

, DoSomething , , , ( ).

, - DoSomething.

+1

try/catch MyClass ...

. ( ) MyClass, .

(MyClass) , .


EntryPointClass , DoIt . MyClass.

: EntryPointClass ( ) , MyClass.

+1

, , ( )

, ( ), , , , , .

, catch ( ), , , .

catch , , .

.

+1

You are actually testing two completely different conditions:

  • Verify that MyClass throws an exception if the argument is invalid
  • Check how EntryPointClass, as a MyClass user, deals with the exception thrown by MyClass
+1
source

All Articles