Jonathan
Jonathan

Reputation: 1296

How to verify that an internal method is called in unit testing?

I do unit testing generally by verifying the state of my object after a method was run, but in some cases i need to test the behavior, not the final state.

For example, i need to add some code that will slow down a method that executes too fast.

I know we can test behavior by mocking objects, but generally we don't mock the object under test, only the collaborators.

So how can I verify in my unit test that myObject.MyMethod is calling for example 10 times myObject.WaitFor15ms ?

Thanks

Upvotes: 0

Views: 684

Answers (1)

Ilya Palkin
Ilya Palkin

Reputation: 15767

Lets say that you need to test MyObject type.

In order to test its internal or protected methods you can create MyObjectForTesting type, override methods or inject some logic that can help you to test MyObject.

    [TestMethod]
    public void DoSmth_InvokesWaitFor15Minutes()
    {
        //arrange
        var list = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
        var target = new MyObjectForTesting();

        // act
        target.DoSmth(list);

        // assert
        target.WaitFor15MinutesCounter.Should().Be(list.Length);
    }

    public class MyObject
    {
        public void DoSmth(int[] list)
        {
            list.ForEach(it => WaitFor15Minutes());
        }

        protected virtual void WaitFor15Minutes()
        {
        }
    }

    public class MyObjectForTesting : MyObject
    {
        public int WaitFor15MinutesCounter { get; private set; }

        protected override void WaitFor15Minutes()
        {
            WaitFor15MinutesCounter++;
        }
    }

Upvotes: 2

Related Questions