单元测试是否应该确保调用特定方法来获得结果? [英] Should unit tests ensure a specific method was called to arrive at the result?

查看:16
本文介绍了单元测试是否应该确保调用特定方法来获得结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定以下类和方法:

public class CarService
{
    private readonly ICarModelService _cardModelService;

    public TestMe(ICarModelService service)
    {
        _service = service;
    }

    public Car Add(string vin)
    {
        var model = _cardModelService.GetByVIN(vin);
        if (model == "Chevy")
            throw new InvalidCarModelException();
        // other logic
    }
}

在测试 Add 方法时,确保(通过 NSubstitute 的 Received 函数) 调用 _cardModelService.GetByVIN(vin) 或我应该只测试异常 InvalidCarModelException 是否被抛出?

When testing the Add method, is it wise to ensure (via NSubstitute's Received function) that the call _cardModelService.GetByVIN(vin) was received or should I only test that the exception InvalidCarModelException was thrown?

这个测试是不是太多了?

Is this testing too much?

推荐答案

单元测试应该准确地涵盖其名称所说的内容 - 执行应用程序中最小的可测试部分.如果您以某种方式依赖其他先决条件,正如您所知 Mocking 是主要用于单元测试.

Unit tests should cover exactly what their name says - exercise the smallest testable part of an application. If you somehow depend on other preconditions, as you know Mocking is primarily used in unit testing.

被测对象可能依赖于其他(复杂)对象.要隔离要测试的对象的行为,请替换其他对象通过模拟真实对象的行为的模拟.如果真实对象不切实际,这将很有用进入单元测试.

An object under test may have dependencies on other (complex) objects. To isolate the behavior of the object you want to test you replace the other objects by mocks that simulate the behavior of the real objects. This is useful if the the real objects are impractical to incorporate into the unit test.

为了避免重复,可以查看我的答案在这里.更具体地说,您需要关注的不是 var 模型 对象.

In order to avoid duplicates, you can look at my answer here. To be more specific, what you need to focus on is not the var model object.

确保收到调用_cardModelService.GetByVIN(vin)

是另一种测试类型的问题,例如系统集成测试.只需使用正面和负面方法对您的 public Car Add(string vin) 进行单元测试.

Is a matter of another testing types, like System integration testing. And just unit test your public Car Add(string vin) with both positive and negative approach.

这篇关于单元测试是否应该确保调用特定方法来获得结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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