Moq를 사용하여 확장 방법 모의
단위 테스트 시나리오에서는 기존 인터페이스에 적용되는 확장 메서드를 모의해야 할 수도 있습니다. 다음 사항을 고려하세요.
<code class="language-csharp">public interface ISomeInterface { void SomeMethod(); } public static class SomeInterfaceExtensions { public static void AnotherMethod(this ISomeInterface someInterface) { // 方法实现 } } public class Caller { private readonly ISomeInterface someInterface; public Caller(ISomeInterface someInterface) { this.someInterface = someInterface; } public void Main() { someInterface.AnotherMethod(); } }</code>
Caller
클래스를 테스트하려면 ISomeInterface
인터페이스를 모의하고 AnotherMethod
확장 메서드에 대한 호출을 확인해야 합니다. 그러나 x => x.AnotherMethod()
을 직접 시뮬레이션하려고 하면
<code class="language-csharp">[Test] public void Main_BasicCall_CallsAnotherMethod() { // Arrange var someInterfaceMock = new Mock<ISomeInterface>(); someInterfaceMock.Setup(x => x.AnotherMethod()).Verifiable(); // 这里会抛出异常 var caller = new Caller(someInterfaceMock.Object); // Act caller.Main(); // Assert someInterfaceMock.Verify(); }</code>
예외 정보:
<code>System.ArgumentException: Invalid setup on a non-member method: x => x.AnotherMethod()</code>
이 문제를 해결하기 위한 한 가지 방법은 확장 메서드에 대한 래퍼 개체를 만드는 것입니다.
<code class="language-csharp">public class AnotherMethodWrapper { public static void CallAnotherMethod(ISomeInterface someInterface) { someInterface.AnotherMethod(); } }</code>
테스트에서 래퍼 메서드를 조롱할 수 있습니다.
<code class="language-csharp">[Test] public void Main_BasicCall_CallsAnotherMethod() { // Arrange var wrapperMock = new Mock<AnotherMethodWrapper>(); wrapperMock.Setup(x => x.CallAnotherMethod(It.IsAny<ISomeInterface>())).Verifiable(); var someInterfaceMock = new Mock<ISomeInterface>(); // 这里需要调整Caller的构造函数,注入wrapperMock.Object // 这部分需要根据实际情况修改,可能需要修改Caller类或者使用其他方法注入依赖 var caller = new Caller(someInterfaceMock.Object); // 此处可能需要修改,注入wrapperMock.Object // Act caller.Main(); // Assert wrapperMock.Verify(); }</code>
래퍼를 사용하면 확장 메서드 호출을 모의하고 단위 테스트할 수 있습니다. 이 예제의 Caller
클래스는 AnotherMethodWrapper
을 사용하도록 수정해야 합니다. 이는 Caller
클래스의 특정 구현에 따라 달라지며, AnotherMethodWrapper
를 삽입하려면 종속성 주입이나 다른 메서드가 필요할 수 있습니다. Caller
.
위 내용은 Moq를 사용하여 단위 테스트에서 확장 메서드를 모의하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!