简体   繁体   English

模拟列表或模拟对象列表

[英]Mocking a list or List of Mock Objects

I have a class that uses a list of objects. 我有一个使用对象列表的类。 How would you mock the list and why? 您将如何模拟列表?为什么? Do you mock the List so that it returns Mock Objects when a list method is called. 您是否在模拟列表,以便在调用列表方法时它返回模拟对象。 Or do you create an instance of the list with mock objects? 还是使用模拟对象创建列表的实例?

Below is a crude code example. 下面是一个简单的代码示例。 So if I mock the List, I would need to know how the list is used and setup the correct returns/expectations on the methods of the list. 因此,如果我模拟列表,则需要知道如何使用列表,并在列表的方法上设置正确的返回值/期望值。 Or with a List of mock objects, I just need to setup the list with mock objects and assert that each mock Subscriber is 'used'. 或使用模拟对象列表,我只需要使用模拟对象设置列表,并断言每个模拟订阅服务器均已“使用”。

I testing that each subscriber is called, in my view latter approach is correct, what is your view? 我测试每个用户都被称为,在我看来后一种方法是正确的,您的看法是什么?

public class Publisher {

    private List<Subscriber> subscribers;

    public void publish() {
        // loop through subscribers
    }

}

Mocking a List of mocks sounds like jumping the shark to me. 模拟一个模拟List听起来像是在跳鲨鱼。 I would say that returning a List of mocks should be sufficient. 我想说,返回一个模拟List就足够了。

You aren't testing the List implementation - you know that works. 您没有测试List实现-您知道这是可行的。 Use it. 用它。

Mock is required when you want to: 当您要执行以下操作时,需要提供模拟:

  1. Instruct a class under your control to perform a predefined behavior (eg returning a known value, throw a pre-defined exception). 指示您控制下的类执行预定义的行为(例如,返回已知值,引发预定义的异常)。
  2. Test a class to make sure it performed the expected behavior. 测试一个类,以确保它执行了预期的行为。

In your case, you certainly don't want to define List to perform any special behavior, neither do you want to test the List class to perform as expected. 在您的情况下,您当然不想定义List来执行任何特殊行为,也不想测试List类来按预期执行。 So you shouldn't create a Mock of the list. 因此,您不应创建列表的模拟。

Your test subject is Subscriber. 您的测试主题是订户。 So you are right, you need a list of mocks of Subscribers. 因此,您说对了,您需要一个订阅者模拟列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM