수색…
비고
Moq는 .NET 용 조롱 라이브러리입니다. 단위 테스트를 용이하게하기 위해 종속성과의 상호 작용을 시뮬레이션 및 검증 할 수 있습니다.
설치 또는 설정
- Moq에 대한 참조를 추가 할 프로젝트를 선택하십시오.
- 이 프로젝트에 대해 Nuget을 엽니 다.
- 검색 상자에 "moq"를 입력하는 것보다 "찾아보기"를 선택하십시오.
- "Moq"를 선택하고 Install을 클릭하십시오.
이 단계를 수행하면 Moq 패키지가 설치되고 선택한 프로젝트 참조에 해당 참조가 추가됩니다. 이 단계를 완료 한 후 Moq는 단위 테스트 프로젝트에서 테스트 클래스 파일에 선언함으로써 간단하게 사용할 수 있습니다.
Using Moq;
Moqs는 테스트 복식입니다.
Mock은 테스트 복식으로, Mock과의 상호 작용을 검증 할 수 있으며 테스트중인 시스템을 대체하기위한 것이 아닙니다. 다음은 Moq의 기능을 예제로 보여줍니다.
// Create the mock
var mock = new Mock<IMockTarget>();
// Configure the mock to do something
mock.SetupGet(x => x.PropertyToMock).Returns("FixedValue");
// Demonstrate that the configuration works
Assert.AreEqual("FixedValue", mock.Object.PropertyToMock);
// Verify that the mock was invoked
mock.VerifyGet(x => x.PropertyToMock);
이 예제는 모의 사용과 관련된 단계를 보여 주지만 모의이 올바르게 설정되고 올바르게 사용되었다는 것을 제외하고는 실제로 아무 것도 테스트하지 않는다는 것을 기억하는 것이 중요합니다. 모의를 사용하는 실제 테스트는 테스트 할 시스템에 모의 정보를 제공합니다. 다음 방법을 테스트하려면 :
public class ClassToTest
{
public string GetPrefixedValue(IMockTarget provider)
{
return "Prefixed:" + provider.PropertyToMock;
}
}
종속 인터페이스의 모의 객체를 생성하는 것이 가능합니다 :
public interface IMockTarget
{
string PropertyToMock { get; }
}
실제로 GetPrefixedValue
메서드의 동작을 확인하는 테스트를 만들려면 :
// Create and configure the mock to return a known value for the property
var mock = new Mock<IMockTarget>();
mock.SetupGet(x => x.PropertyToMock).Returns("FixedValue");
// Create an instance of the class to test
var sut = new ClassToTest();
// Invoke the method to test, supplying the mocked instance
var actualValue = sut.GetPrefixedValue(mock.Object);
// Validate that the calculated value is correct
Assert.AreEqual("Prefixed:FixedValue", actualValue);
// Depending on what your method does, the mock can then be interrogated to
// validate that the property getter was called. In this instance, it's
// unnecessary since we're validating it via the calculated value.
mock.VerifyGet(x => x.PropertyToMock);
Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow