模拟C#函数代理



我有个问题,我有一个使用Func委托解决的依赖项,在这种情况下我如何使用moq?

public Func<string, IMylogic> MyLogic { get; set; }

定义如下:

public class Startup : FunctionsStartup
{
public override void Configure(IFunctionsHostBuilder builder)
{           
builder.Services.AddTransient(Factory);
}
private static Func<IServiceProvider, Func<string, IMyLogic>> Factory =>
service =>
{
return key =>
{
return new MyLogic(key, new System.Net.Http.HttpClient());
};
};
}

这只是关于测试应该如何工作的一个想法:

public class ExecuteEmitLogicTest
{
ExecuteTransactionCommand ExecuteEmitCommand;
Dictionary<string, StringValues> queryString;
Mock<Func<string, IMyLogic>> Concrete;

[Fact]
public async Task ExecuteEmit()
{ 
var Concrete = mockFactory.Create<Func<string, IMyLogic>>(MockBehavior.Loose);
Concrete.Setup(c => c.Invoke(ConcreteTInfo).Execute(request, Guid.Parse(sessionId))).Returns(Task.FromResult(pol));
ExecuteEmitCommand = new ExecuteTransactionCommand(Concrete.Object);
var response = await ExecuteEmitCommand.ExecuteAndEmit(queryString, ConcreteTInfo.ApiSkrUrl, ConcreteTInfo.SkrKey, FIXED_HASH);
Assert.True(response.IsValid);
}
}

我不理解带有<字符串,接口>功能,但我想测试看起来更像这样:

public interface IMyLogic { int GetX(); }
...
Mock<IMyLogic> mockLogic = new Mock<IMyLogic>(MockBehavior.Strict);
// For the unit test always return the mock as 
// we are *not* testing the IMyLogic provider function
Func<string, IMyLogic> f = (string _) => mockLogic.Object;
mockLogic.Setup(ml => ml.GetX()).Returns(7);
var tested = new ExecuteTransactionCommand(f);
var response = await tested.ExecuteAndEmit(queryString, ConcreteTInfo.ApiSkrUrl, ConcreteTInfo.SkrKey, FIXED_HASH);
// Asserts here

相关内容

  • 没有找到相关文章

最新更新