0

Having tested all my previous code manually, I was trying to get some experience with using unit test framework. Based on some initial study, I am using Microsoft Tests and justMock Lite. But, then I ran into a fairly simple scenario (from user's point of view), which I am unable handle because of just using the open source version restriction. Here is the scenario which is used to send mail.

IEmailService interface

public interface IEmailService {
    bool SendEmail(string recipient, string message, string from);
}

WebMailService implementation

public class WebEmailService : IEmailService {

    public bool SendEmail(string recipient, string message, string from) {
        try {
            MailMessage mail = new MailMessage(from, recipient,"",message);
            SmtpClient client = new SmtpClient();
            client.Send(mail);//This call needs to be mocked
            return true;
        }
        catch (Exception) {
            return false;
        }
    }
}

So I was trying to test the above using JustMock Lite as given below

Unit Test

[TestMethod]
public void SendMail_WhenNoExceptionThrown_ReturnsTrue() {
    IEmailService mailService = new WebEmailService();
    var smtpClient = Mock.Create<SmtpClient>();
    Mock.Arrange(() => smtpClient.Send(Arg.IsAny<MailMessage>())).DoNothing().MustBeCalled();
    bool returnCode = mailService.SendEmail("recipient", "message", "from");
    Assert.AreEqual(true, returnCode);
}

And this resulted into an exception, and I realized that this kind of mocking .Net methods are not supported in the open source product(JustMock Lite).

So, is there a way to get around such scenarios using open source mocking frameworks, or is it too much for a asking.

Note: I have already gone through option of wrapping the SmtpClient into a wrapper, and extract interface for the same. But, I am just curious to know other approaches where we work without wrapping SmtpClient object.

Community
  • 1
  • 1
Jatin
  • 4,023
  • 10
  • 60
  • 107

1 Answers1

0

I suggest if the tool has limitation don't use it. With I.eJustMock Unless you willing to pay for it

You scenario is pretty trivial I think so you have couple of options

Wrap your SmtpClient methods in an interface and expose them so you can

A. Use poor man mocking / hand written manual mocks.

I.e ISmtpClientService.SendEmail(...)

You create testable SmtpClient service which implements ISmtpClientService. The REAL implementation of this service is a wrapper around real SmtpClient

Or try inheriting from real SmtpClient - not sure this is possible I.e sealed if not you can creating a testable version without having to wrap in an interface as above

B. Just Mock might be able to stub these virtual methods. Pretty sure they do allow clients to stub virtual methods like other free frameworks

Spock
  • 7,009
  • 1
  • 41
  • 60