Search code examples
c#unit-testingmockingfakeiteasymoq-3

C# mock not working in actual code


I currently have the following method with code:

public bool SendMail(ref MailData data)
    SmtpClient smtpClient = this.smtpClient;
    Console.WriteLine("SMTP CLIENT: " + smtpClient.ToString());
    Console.WriteLine("SMTP PORT: " + smtpClient.Port);
    Console.WriteLine("SMTP HOST: " + smtpClient.Host);
}

With the following testcode calling it:

 public class MockSmtpClient : SmtpClient {
    public virtual void Send(MailMessage mailMessage) {
    }
    public virtual string Host
    {
        get
        {
            return Host;
        }
    }
    public virtual int Port
    {
        get
        {
           return Port;
        }
    }
 }

 ... (actual testcode:) ...


 MailData mailData = new MailData {
   HostAddress = "mydomain.com",
 };

 var mockSmtpClient = A.Fake<MockSmtpClient>();
 var mailerMock = new Mailer();

 // Setup
 It.IsAny<SmtpDeliveryMethod>())).Returns(mockSmtpClient.Object);
 A.CallTo(() => mockSmtpClient.Host).Returns(mailData.HostAddress);
 A.CallTo(() => mockSmtpClient.Port).Returns(22);

 // Act
 mailerMock.smtpClient = mockSmtpClient;
 mailerMock.SendMail(ref mailData);
 Console.WriteLine("MOCK SMTP CLIENT FROM TEST: " + mockSmtpClient);
 Console.WriteLine("SMTP HOST FROM UT: " + mockSmtpClient.Host);
 Console.WriteLine("SMTP PORT FROM UT: " + mockSmtpClient.Port);

When I call the mock object's host and port in the actual code it is giving me \

SMTP CLIENT: Faked ServiCommTests.MockSmtpClient
SMTP PORT: 25
SMTP HOST: 

However, if I call the mock's properties from the test code it's giving me the correct stubbed properties:

MOCK SMTP CLIENT FROM TEST: Faked ServiCommTests.MockSmtpClient
SMTP HOST FROM UT: mydomain.com
SMTP PORT FROM UT: 22

As you can see, in the actual code it is returning no host and default port while in the testcode it is giving me the correct stubbed properties from the mocking framework, while the object is the same in both environments.

It goes exactly the same when I use the mocking framework Moq instead of FakeItEasy (as in the example).

Thanks in advance.


Solution

  • It turned out that it worked when I changed my MockSmtpClient class to an interface. Moq and Fakeiteasy apparantly don't support mocking normal classes.