简体   繁体   中英

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. I would say that returning a List of mocks should be sufficient.

You aren't testing the List implementation - you know that works. 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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