How to test classes using access to databases and Exchange Server?

I just finished a tutorial on developing tests in C # with Nunit. Now I want to use unit tests for my new project, but I'm having difficulty writing tests. What is the best way to write unit tests for classes related to accessing a database or web services? Can someone give me some lessons / examples of unit tests?

+3
source share
1 answer
  • Create an interface that wraps the functionality of calling db, sending emails, ...
  • Write an implementation of your class and load this class into a dependent class using DI
  • Use the Mock framework to create a Mock object and set it to expectations in the unit test.

Here is an example of pseudo code (the Moq layout generator used here ):

interface IEmailer
{
    void Send(Email email);
}

class RealEmailer : IEmailer
{
    public void Send(Email email)
    {
        // send
    }
}

class UsesEmailer
{
    private IEmailer _emailer;

    public UsesEmailer(IEmailer emailer)
    {
        _emailer = emailer;
    }


    public foo(Email email)
    {
        // does other stuff
        // ...
        // now sends email
        _emailer.Send(email);
    }

}

class MyUnitTest
{
    [Test]
    public Test_foo()
    {
        Mock<IEmailer> mock = new Mock<IEmailer>();
        Email m = new Email();
        mock.Expect(e => e.Send(It.Is<Email>(m)));
        UsesEmailer u = new UsesEmailer(mock.Object);
        u.Send(m);
        mock.Verify();
    }

}

UPDATE

Now, if you are testing RealEmailer, there are several ways, but basically you will have to configure the test to send you an email, and you will check. This is not quite a unit test, since you not only check your code, but also the configuration, network, exchange server ... in fact, if you make it RealEmailersmall, having a small code, you can skip the block test for it.

+5
source

Source: https://habr.com/ru/post/1780427/


All Articles