0

I want to test my code which is depend on Microsoft logging and i want to mock it or by pass it. in this method i am validating the input.

it gives me below error "The LogWriter has not been set for the Logger static class. Set it invoking the Logger.SetLogWriter method." My code is as below.

public HttpResponseMessage Patch(long Id)
    {
        using (new Tracer(GetType().Namespace))
        {
            EnterpriseHeader entHeader = Request.GetEnterpriseHeaders();
            Request.LogApiRequestReceived(_logger, entHeader, GetType().Name);
            Request.VerifyIdFormat((ulong)CustomerId);
            _bussinessObject.PatchData(Id, entHeader);
            return Request.CreateResponse(HttpStatusCode.OK);
        }
    }

In Mocking Method i am writing below code. Ilogger is our custom logger which i am able to mock but "New Tracer(Gettype().NameSpace)" not able to mock.

var     mocklogger = new Mock<ILogger>();      
var mockTracer = new Mock<ITracer>();

        mockTracer.Setup(x => x.Tracer(GetType().Namespace));

        var Controller = new Controller(mockBO.Object, mocklogger.Object);
        Controller.Request = AddHttpRequestForHeaders();

        var Results = Controller.GetById(1517, true, false);

now i want to mock Tracer in Moq.

If i Mock the obove code in Moq it gives me Error i.e "Additional information: Invalid setup on a non-virtual (overridable in VB) member: mock => mock.GetType()"

and my code in Moq is

var mockTracer = new Mock<Tracer>();

        mockTracer.Setup(x => x.GetType().Namespace);

Thanks,

yogs
  • 23
  • 1
  • 9
  • 1
    Logger is a static class which makes it difficult to mock and test in unit tests. Abstract the logger behind an interface that can be mocked during tests. Provide more context in terms of your code. Not enough information has been given to be able to provide you with a good answer. – Nkosi Feb 13 '17 at 10:25
  • i am not able mock "New Tracer(GetType().NameSpace)". please see the above code. Thanks – yogs Feb 14 '17 at 07:28

1 Answers1

0

It is sometimes better not to use a mocking framework to create a mock. Especially singleton staff is difficult to mock. In this case you should probably just configure the log to do just nothing. This kind of test double is called fake: https://www.martinfowler.com/bliki/TestDouble.html

See this article to create fake LogWriter: https://martinwilley.com/net/code/entliblognoconfig.html

George Mamaladze
  • 7,593
  • 2
  • 36
  • 52