Unit testing and checking private variable value

后端 未结 6 1705
难免孤独
难免孤独 2020-11-27 04:27

I am writing unit tests with C#, NUnit and Rhino Mocks. Here are the relevant parts of a class I am testing:

public class ClassToBeTested
{
    private IList         


        
6条回答
  •  误落风尘
    2020-11-27 04:59

    If the list is an internal implementation detail (and it seems to be), then you shouldn't test it.

    A good question is, what is the behavior that would be expected if the item was added to the list? This may require another method to trigger it.

        public void TestMyClass()
        {
            MyClass c = new MyClass();
            MyOtherClass other = new MyOtherClass();
            c.Save(other);
    
            var result = c.Retrieve();
            Assert.IsTrue(result.Contains(other));
        }
    

    In this case, i'm asserting that the correct, externally visible behavior, is that after saving the object, it will be included in the retrieved collection.

    If the result is that, in the future, the passed-in object should have a call made to it in certain circumstances, then you might have something like this (please forgive pseudo-API):

        public void TestMyClass()
        {
            MyClass c = new MyClass();
            IThing other = GetMock();
            c.Save(other);
    
            c.DoSomething();
            other.AssertWasCalled(o => o.SomeMethod());
        }
    

    In both cases, you're testing the externally visible behavior of the class, not the internal implementation.

提交回复
热议问题