如何模拟 class 变量

How to Mock class variable

我正在使用 xUnit 和 Moq 编写测试用例。

目前我正在为遥测编写测试用例class。

 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);
        }

    }

在测试 class 中如何模拟,键 variable.I 用于编写下面的模拟方法代码。

          [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);
            }

如何模拟变量。

您可以使用 SetupSetupPropertySetupGet 来实现此目的,具体取决于您的需要:

mockTelemetryClient.Setup(x => x.key).Returns("foo");

mockTelemetryClient.SetupProperty(x => x.key, "foo");

mockTelemetryClient.SetupGet(x => x.key).Returns("foo");

正如Alves RC所指出的,假定key 属性存在于ITelemetryClientMock接口中。