模拟框架网站中给出的大多数示例都是模拟接口.让我说我正在使用的NSubstitute,他们所有的模拟示例都是模拟界面.
但实际上,我看到一些开发人员嘲笑混凝土类.是否建议模拟混凝土类?
在 Java 中,当我有一个类调用其他类的静态方法时,我总是封装它,这样我就可以测试它,而无需实际访问该真实资源。例如:
public class HasSomeStaticCall
{
public HasSomeStaticCall()
{
this.something = callStaticThing();
}
protected String callStaticThing()
{
return SomeThirdParty.getFromStaticMethod();
{
}
Run Code Online (Sandbox Code Playgroud)
在Java 中,我可以使用Spy而不是Mock然后使用除该方法之外的所有实际方法。
例子:
public void test()
{
HasSomeStaticCall obj = Mockito.spy( HasSomeStaticCall.class );
//Only mock this one method
Mockito.doReturn( "SomeValue" ).when( obj ).callStaticThing();
}
Run Code Online (Sandbox Code Playgroud)
我将如何在 C# 中执行此操作?(我使用的是.Net Framework 4.7.x,而不是.Net Core)
我在 Microsoft Docs 上阅读了一篇关于在 .NET Azure Functions 中使用依赖项注入的文章。
一切正常,正如您在文章中看到的,它注册了 CosmosClient
builder.Services.AddSingleton((s) => {
return new CosmosClient(Environment.GetEnvironmentVariable("COSMOSDB_CONNECTIONSTRING"));
});
Run Code Online (Sandbox Code Playgroud)
问题是,如何在我的函数中使用 Cosmos Client?我不想每次都创建 Cosmos Client 实例。
public class CosmosDbFunction
{
public CosmosDbFunction()
{
}
[FunctionName("CosmosDbFunction")]
public async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
// TODO: do something later
return null;
}
}
Run Code Online (Sandbox Code Playgroud) 我有一个时间触发的 Azure 函数,我想用 XUnit 和 MOQ 测试它。
虽然我知道我需要Run使用类的实例来调用该类的方法,但请说明funTimeTriggeredObj在哪里
funTimeTriggered funTimeTriggeredObj = new funTimeTriggered(queueSchedulerMock.Object, telemetryHelperMock.Object)
Run Code Online (Sandbox Code Playgroud)
喜欢
funTimeTriggeredObj.Run(param1, param2, loggerMock.Object)
Run Code Online (Sandbox Code Playgroud)
在哪里
private Mock<ILogger> loggerMock = new Mock<ILogger>()
Run Code Online (Sandbox Code Playgroud)
我不知道我应该怎么嘲笑param1与param2它们TimerInfo和ExecutionContext分别的对象。
我问的原因是因为“TimerInfo”和“ExecutionContext”都没有实现任何可以模拟的接口。
下面是我的实际功能实现。任何帮助将不胜感激。
using System;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Logging;
public class funTimeTriggered
{
private string _invocationID;
private readonly IQueueScheduler _queueScheduler;
private readonly ITelemetryHelper _telemetryHelper;
public funTimeTriggered(IQueueScheduler queueScheduler, ITelemetryHelper telemetryHelper)
{
_queueScheduler = queueScheduler;
_telemetryHelper = telemetryHelper;
}
[FunctionName("funTimeTriggered")]
public async Task …Run Code Online (Sandbox Code Playgroud)