-2

I have a class FileGenerator, and I'm writing a test for the generateFile() method that should do the following:

1) it should call the static method getBlockImpl(FileTypeEnum) on BlockAbstractFactory

2) it should populate variable blockList from the subclass method getBlocks()

3) it should call a static method createFile from a final helper class FileHelper passing a String parameter

4) it should call the run method of each BlockController in the blockList

I'm trying to use TDD to test the last scenario of my method. I have a list of BlockController objects that implement Runnable, and I need to verify if each one calls the run() method.

Here's what I'm trying to do:

public class FileGenerator {
// private fields with Getters and Setters

    public void generateBlocks() {
        // 1,2 get the block manager that will return the BlockController list
        blockManager = BlockAbstractFactory.getManager(fileType);
        blockList = blockManager.getBlocks();
        // create a file using FileHelper
        FileHelper.createFile(path);

        // What I want to test:
        // for each BlockController in the blockList, call the run() method
    }
}

I am using Junit and Mockito. In the Mockito's documentation, they only show how to mock a List and verify method calls on the List (such as add(T), remove(T) etc), not its objects.

Any idea how I can do this?

4

1 回答 1

1

I found the answer before I posted the question. It's actually quite simple.

First, you need to mock the object you'll have using Mockito:

final BlockController mockedBlock = mock(BlockController.class);

Next, create the List using your mocked object (below I have create a list of 3 mocked objects of type BlockController):

List<BlockController> myBlockList = Arrays.asList(mockedBlock, mockedBlock, mockedBlock);

Set the list in your tested class to the list of mocked objects before calling the method:

fileGenerator.setBlockList(myBlockList);
fileGenerator.generateBlocks();

Now, with Mockito, just verify if the number of calls to the bar method match the size of your List:

verify( myBlockList, times(myBlockList.size()) ).run();

This is what it looks like in the end (my FileGenerator object is created in a @Before method):

@Test
public testShouldCallRunForEachBlock() {
    final BlockController mockedBlock = mock(BlockController.class);
    List<BlockController> myBlockList = Arrays.asList(mockedBlock, mockedBlock, mockedBlock);

    fileGenerator.setBlockList(myBlockList);
    fileGenerator.generateBlocks();

    verify( myBlockList, times(myBlockList.size()) ).run();
}

And that's it. Now the test will fail until the a loop is implemented.

于 2013-03-18T17:31:46.027 回答