我有一个预先存在的界面......
public interface ISomeInterface
{
void SomeMethod();
}
Run Code Online (Sandbox Code Playgroud)
并且我使用mixin扩展了这个表面...
public static class SomeInterfaceExtensions
{
public static void AnotherMethod(this ISomeInterface someInterface)
{
// Implementation here
}
}
Run Code Online (Sandbox Code Playgroud)
我有一个叫这个我要测试的课程...
public class Caller
{
private readonly ISomeInterface someInterface;
public Caller(ISomeInterface someInterface)
{
this.someInterface = someInterface;
}
public void Main()
{
someInterface.AnotherMethod();
}
}
Run Code Online (Sandbox Code Playgroud)
和测试,我想模拟界面并验证对扩展方法的调用...
[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();
}
Run Code Online (Sandbox Code Playgroud)
然而,运行此测试会产生异常......
System.ArgumentException: …Run Code Online (Sandbox Code Playgroud) 我正在尝试为我的控制器类编写单元测试,它使用以下命令检索令牌:
string token = await HttpContext.GetTokenAsync("access_token");
Run Code Online (Sandbox Code Playgroud)
因此,我用以下代码模拟了 HttpContext:
public static HttpContext MakeFakeContext()
{
var serviceProvider = new Mock<IServiceProvider>();
var authservice = new Mock<IAuthenticationService>();
authservice.Setup(_ => _.GetTokenAsync(It.IsAny<HttpContext>(), It.IsAny<string>())).Returns(Task.FromResult("token"));
serviceProvider.Setup(_ => _.GetService(typeof(IAuthenticationService))).Returns(authservice);
return new DefaultHttpContext
{
RequestServices = serviceProvider.Object
};
}
Run Code Online (Sandbox Code Playgroud)
我正在设置模拟上下文:
var mockcontext = MakeFakeContext();
unitUnderTest.ControllerContext = new ControllerContext
{
HttpContext = mockcontext
};
Run Code Online (Sandbox Code Playgroud)
现在,当我运行单元测试时,出现以下错误:
System.NotSupportedException:不支持的表达式:_ => _.GetTokenAsync(It.IsAny(), It.IsAny()) 扩展方法(此处:AuthenticationTokenExtensions.GetTokenAsync)不能用于设置/验证表达式。
在我的研究过程中,我偶然发现了一些解决方案,您可以在其中模拟引擎盖下不属于扩展的特定部分。这些是其中一些:Moq IServiceProvider / IServiceScope,如何对 HttpContext.SignInAsync() 进行单元测试?. 第二个显示了类似的问题,在我尝试后似乎有效。但由于某种原因,它不适用于 GetTokenAsync 方法。
大家有什么提示吗?