cha*_*har 0 .net c# moq xunit .net-core
我正在使用 xUnit 和 Moq 编写测试用例。
目前我正在为遥测类编写测试用例。
public class TelemetryClientMock : ITelemetryClientMock
{
public string key { get; set; } //I want to mock key variable.
private TelemetryClient telemetry;
public TelemetryClientMock( )
{
telemetry = new TelemetryClient() { InstrumentationKey = key };
}
public void TrackException(Exception exceptionInstance, IDictionary<string, string> properties = null)
{
telemetry.TrackException(exceptionInstance, properties);
}
public void TrackEvent(string eventLog)
{
telemetry.TrackEvent(eventLog);
}
}
Run Code Online (Sandbox Code Playgroud)
在测试类中,我如何模拟关键变量。我曾经为模拟方法编写以下代码。
[Fact]
public void TrackException_Success()
{
Exception ex=null;
IDictionary<string, string> dict = null;
var reader = new Mock<ITelemetryClientMock>();
var mockTelemetryClient = new Mock<ITelemetryClientMock>();
//mocking method below
mockTelemetryClient
.Setup(data => data.TrackException(It.IsAny<Exception>(), It.IsAny<IDictionary<string, string>>()));
this._iAppTelemetry = new AppTelemetry(mockTelemetryClient.Object);
this._iAppTelemetry.TrackException(ex,dict);
}
Run Code Online (Sandbox Code Playgroud)
我如何模拟变量。
您可以根据需要使用Setup, SetupProperty, , 来实现此目的:SetupGet
mockTelemetryClient.Setup(x => x.key).Returns("foo");
Run Code Online (Sandbox Code Playgroud)
或者
mockTelemetryClient.SetupProperty(x => x.key, "foo");
Run Code Online (Sandbox Code Playgroud)
或者
mockTelemetryClient.SetupGet(x => x.key).Returns("foo");
Run Code Online (Sandbox Code Playgroud)
正如Alves RC指出的,假设key属性存在于ITelemetryClientMock接口中。
| 归档时间: |
|
| 查看次数: |
3769 次 |
| 最近记录: |