0

I want to test that a method Foo, that calls three private methods boo1, boo2, boo3 is indeed calling them in this exact order (this is a simplification of the real scenario).

To test the sequence I am planning on using InSequence method of the Mock object.

To test the private method i am planning on using the PrivateObject class.

I have no idea how to combine those two; here what I've tried so far, but it doesn't seem to work!

public class TestedClass
{
    private void _boo1(object someParam)
    {
        //some logic
    }
    private void _boo2(object someParam)
    {
        //some logic
    }
    private void _boo3(object someParam)
    {
        //some logic
    }
    public void Foo(object someParam)
    {
        _boo1(someParam);
        _boo2(someParam);
        _boo3(someParam);
    }
}

And here the test method that I've created so far:

[TestMethod]
public void TestSequence()
{
        var sequence = new MockSequence();
        var mockedObject = new Mock<TestedClass>();
        PrivateObject obj = new PrivateObject(mockedObject);
        mockedObject.Object.Foo(It.IsAny<Object>());

        mockedObject.InSequence(sequence).Setup(x => obj.Invoke("_boo1", BindingFlags.Default, It.IsAny<Object>()));
        mockedObject.InSequence(sequence).Setup(x => obj.Invoke("_boo2", BindingFlags.Default, It.IsAny<Object>()));
        mockedObject.InSequence(sequence).Setup(x => obj.Invoke("_boo3", BindingFlags.Default, It.IsAny<Object>()));
}

Any help would be appreciated.

  • Look at this problem. Maybe it is similar to yours: https://stackoverflow.com/questions/10602264/using-moq-to-verify-calls-are-made-in-the-correct-order – RichyP7 Nov 16 '18 at 16:45
  • Thanks, but i am looking to test the sequence of private methods not public ones –  Nov 16 '18 at 23:20
  • A private method(s) is an implementation detail that should be hidden to the users of the class. Testing private methods breaks encapsulation. In your case if you change the implementation of `Foo`, you must change your unit test too, which makes absolutely no sense at all. – Hasan Emrah Süngü Nov 19 '18 at 06:55
  • If you would not mock your private methods: Would there be some criteria by which you could observe whether the three methods were called in the proper order? – Dirk Herrmann Feb 17 '19 at 16:11

1 Answers1

0

Why not use System.IO to write status messages to a log file? You can also use System.Diagnostics to get the name of the method you're currently in:

string methodName = new StackTrace().GetFrame(0).GetMethod().Name
Mike Bruno
  • 600
  • 2
  • 9
  • 26
  • but this is a unit test! i have to change the tested method for that ? –  Nov 17 '18 at 17:46