开发者

How do I test classes involving Database and Exchange Server Access?

开发者 https://www.devze.com 2023-01-30 12:23 出处:网络
I just finished a tutorial for test driven development in c# with Nunit. I now want to use unit tests for my new project, but i have difficulties writing tests.

I just finished a tutorial for test driven development in c# with Nunit. I now want to use unit tests for my new project, but i have difficulties writing tests. How do I best write unit tests for classes involving Database开发者_如何学C or web-service access? Can someone give me some classes/unit-tests examples?


  • Design an interface wrapping the functionality of calling db, sending email, ...
  • Write an implementation of your class and load the this class in the dependent class using DI
  • Use a Mock framework to create a Mock object and set expectations on it in your unit test.

Here is a sample pseudo-code (Mock generator used here is Moq framework):

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 a few ways but basically you will have to setup the test to send you en email and you check in the . This is not quite a unit test since you are not only testing your code but the configuration, network, exchange server, ... in fact if you make RealEmailer small having little code, you can skip writing unit test for it.

0

精彩评论

暂无评论...
验证码 换一张
取 消