Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit testing and the scope of objects - how to test private/internal methods etc?

Let's say I have a project that is a class library. I have a class in that library and this class has some methods that are used inside the class only. Like this:

public class MyClass
{
  public void MyPublicMethod
  {
    int k

    // do something ...

    int z = MyInternalMethod(k);
    // do something else ...

  }

  internal int MyInternalMethod(int i)
  {
        // do something ...

  }
}

Now I want to write unit tests for these methods. I would create a "Unit Tests" project, reference the nunit from it and write something like this

[TestFixture]
public class UnitTests
{
  private MyClass myClass;

  [SetUp]
  public void SetupTest
  {
    myClass = new MyClass();
  }

  [Test]
  public void TestMyInternalMethod
  {
    int z = 100;
    int k = myClass.MyInternalMethod(z); //CAN NOT DO THIS!
    Assert.AreEqual(k, 100000);
  }

  [TearDown]
  public void TearDown
  {
    myClass = null;
  }
}

Of course, I can not do this, because of the MyInternalMethod scope. What would be the proper way to handle this situation?

like image 706
Evgeny Avatar asked Sep 02 '09 00:09

Evgeny


1 Answers

Guess it depends on your idea of what a unit is, right? I generally write unit tests for the accessible interface and ignore the private stuff. I've worked with people who will make private things protected (java) for unit test access. I really dislike that approach because it sacrifices the cleanness of the class design for test access.

like image 167
Peter Cardona Avatar answered Oct 16 '22 23:10

Peter Cardona