2

In one of my running class currently i have:

void run() {
    Food food = new FoodBuilder(apple, peach, grape)
                    .build();
    food.eatFood();

My FoodBuilder class is like this:

public class FoodBuilder implements FoodInterface {
    private Food food = new Food();

    public FoodBuilder(Apple apple, Peach peach, Grape graph) {
        food.add(apple);
        food.add(peach);
        food.add(graph);
    }

    @Override
    public Food build() {
        return food;
    } 

And my FoodInterface is:

public interface FoodInterface {
    Food build();
}

Now, I can't change the structure of this class, but I need to mock the food so I can bypass some permission issues in my service when calling food.eatFood(), basically I don't want to actually call food.eatFood(), instead I want to mock food so i can do doNothing().when(food.eatFood()).

I am using PowerMockito and my code is like this:

@RunWith(PowerMockRunner.class)
@PrepareForTest({FoodBuilder.class})
public class MyTest() {
    @Test
    public void mytest() {
        Food food = Mockito.mock(Food.class);
        FoodBuilder builder = Mockito.mock(FoodBuilder.class);
        when(builder.build()).thenReturn(food);

        doNothing().when(food).eatFood(); // This doesn't work! Because the food object is not a mock, instead it is a real object
    }
}

When I am running the test the food object is not a mock that I wanted, instead it is a real object that's being created so I can't tell food.eatFood() to doNothing().

What am I missing?

OPK
  • 4,120
  • 6
  • 36
  • 66

1 Answers1

0

You can use PowerMockito's whenNew functionality to intercept the constructor call.

@Test
public void test() throws Exception {

    Food food = Mockito.mock(Food.class);
    Mockito.doNothing().when(food).eatFood();

    FoodBuilder builder = Mockito.mock(FoodBuilder.class); 
    Mockito.when(builder.build()).thenReturn(food);

    PowerMockito.whenNew(FoodBuilder.class)
                .withArguments(any(Apple.class),any(Peach.class),any(Grape.class))
                .thenReturn(builder);

    run();
}
second
  • 4,069
  • 2
  • 9
  • 24