質問

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.

役に立ちましたか?

解決

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.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top