1

How do i write a just mocked unit test for this scenario?

Private Method1

{

  //calls private method - Method2
}

So that when i mock Method1, i need to again mock internally Method2.

I use form's private accessor to create a unit test, for ex.

FormName_accessor target=new FormName_accessor();

and then use that target.Method1 to call inside my unit test.

Sharpeye500
  • 8,775
  • 25
  • 95
  • 143

1 Answers1

3

Here is an example of mocking private methods of a class and verifying that they are called.

public class Item
{
    public void Update()
    {
        Save();
    }

    private void Save()
    {
        Validate();
        /// Save something
    }

    private void Validate()
    {
        /// Validate something
    }
}

[Fact]
public void EnsureNestedPrivateMethodsAreCalled()
{
    // Arrange
    Item item = Mock.Create<Item>();
    Mock.Arrange(() => item.Update()).CallOriginal().MustBeCalled();
    Mock.NonPublic.Arrange(item, "Save").CallOriginal().MustBeCalled();
    Mock.NonPublic.Arrange(item, "Validate").DoNothing().MustBeCalled();

    // Act
    item.Update();

    // Assert
    Mock.Assert(item);
}

Note that when arranging the mock you want to ensure that the original Update and Save methods are called. You only want to stub out functionality that you aren't testing. In this case, we are testing that calling Update results in calls to the private members Save and Validate. We are not testing the implementation of the Validate method.

Kevin Babcock
  • 10,187
  • 19
  • 69
  • 89
  • say, `Update` contains some additional logic and finally calls `Save`. at this time, if i just want to test the implementation of `Update`, do i need to mock away the `Save`? – pinopino Sep 25 '14 at 09:46