我是否需要为仅在存储库类中调用方法的服务类中的方法编写单元测试? [英] Do I need to write a unit test for a method within service class that only calls a method within repository class?

查看:50
本文介绍了我是否需要为仅在存储库类中调用方法的服务类中的方法编写单元测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例

我有一个存储库类(DAL):

I have a repository class (DAL):

public class MyRepository : IMyRepository
{
    public void Delete(int itemId)
    {
        // creates a concrete EF context class
        // deletes the object by calling context.DeleteObject()
    }

    // other methods
}

我也有一个服务类别(BLL):

I also have a service class (BLL):

public class MyService
{
    private IMyRepository localRepository;

    public MyService(IMyRepository instance)
    {
        this.localRepository = instance;
    }

    public void Delete(int itemId)
    {
        instance.Delete(itemId);
    }

    // other methods
}

为MyRepository创建单元测试比实现它要花费更多的时间,因为我必须模拟实体框架上下文.

Creating a unit test for MyRepository would take much more time than implementing it, because I would have to mock Entity Framework context.

但是为MyService创建单元测试似乎是胡说八道,因为它仅调用存储库.我所能检查的只是验证它是否确实调用了存储库Delete方法.

But creating a unit test for MyService seems nonsense, because it only calls into Repository. All I could check is to verify if it did actually call repository Delete method.

问题

您如何建议对这对Delete方法进行单元测试.两个都?一?没有?你会测试什么?

How would you suggest to unit test these pair of Delete methods. Both? One? None? And what would you test?

推荐答案

是的,我一定会为服务层编写单元测试.造成这种情况的原因是,您不仅在测试自己的实现现在是否有效,而且还在测试它在将来仍将继续工作.

Yes, I would definitely write a unit test for the Service Layer. The reason for this is because, you're not just testing that your implementation works now, but you're also testing that it will continue to work in the future.

这是一个至关重要的概念.如果以后有人来更改您的ServiceLayer,并且没有任何单元测试,您如何验证该功能是否继续起作用?

This is a vital concept to understand. If someone comes along later on and changes your ServiceLayer, and there's no unit test, how can you verify that the functionality continues to work?

我还将为您的DAL编写测试,但我会将其放在称为DataTests之类的单独程序集中.此处的目的是在程序集中隔离您的关注点.单元测试应该与您的DAL无关.

I would also write tests for your DAL, but I would put those in a separate assembly called DataTests or something. The purpose here is to isolate your concerns across assemblies. Unit Tests shouldn't be concerned with your DAL, really.

这篇关于我是否需要为仅在存储库类中调用方法的服务类中的方法编写单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆