수색…


자동 스터 빙 속성

가끔은 클래스 나 인터페이스를 조롱하고 그 속성이 단순한 getter와 setter 인 것처럼 행동하게하려는 경우가 있습니다. 이것이 일반적인 요구 사항이므로, Moq는 모의 (mock)의 모든 속성을 설정하여 값을 저장하고 검색하는 단축키 메서드를 제공합니다.

// SetupAllProperties tells mock to implement setter/getter funcationality
var userMock = new Mock<IUser>().SetupAllProperties();

// Invoke the code to test
SetPropertiesOfUser(userMock.Object);

// Validate properties have been set
Assert.AreEqual(5, userMock.Object.Id);
Assert.AreEqual("SomeName", userMock.Object.Name);

완전성을 위해 테스트중인 코드는 다음과 같습니다.

void SetPropertiesOfUser(IUser user)
{
    user.Id = 5;
    user.Name = "SomeName";
}

개인 설정자가있는 속성

때로는 private setter가있는 클래스의 모의 객체를 만들고 싶을 때가 있습니다.

public class MockTarget
{
    public virtual string PropertyToMock { get; private set; }
}

또는 getter만을 정의하는 인터페이스 :

public interface MockTarget
{
    string PropertyToMock { get; }
}

두 경우 모두 setter를 무시하고 getter 속성을 설정하여 원하는 값을 반환 할 수 있습니다.

var mock = new Mock<MockTarget>();
mock.SetupGet(x => x.PropertyToMock).Returns("ExpectedValue");

Assert.AreEqual("ExpectedValue", mock.Object.PropertyToMock);


Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow