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?