문제

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