0

I am writing test cases using xUnit and Moq.

Currently I am writing test case for Telemetry 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);
        }

    }

In Test class how can I mock, key variable.I used to write below code for mocking method.

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

How can I mock variable.

1 Answer 1

5

You can achieve this using Setup, SetupProperty, SetupGet, depending on what you want:

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

or

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

or

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

As Alves RC pointed out, it is assumed that key property exists in ITelemetryClientMock interface.

Sign up to request clarification or add additional context in comments.

1 Comment

Your answer is correct but I think you could add the following to make sure whatever they're attempting to Mock is "Mockable": "In order to Moq to be able to Mock anything it should be either an Interface or a virtual Property"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.