如何模拟由类生成器创建的对象?

时间:2019-07-31 04:41:14

标签: java junit mocking mockito powermockito

目前在我正在跑步的一门课中,我有:

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

我的FoodBuilder类是这样的:

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;
    } 

我的FoodInterface是:

public interface FoodInterface {
    Food build();
}

现在,我无法更改此类的结构,但是我需要模拟food,以便在调用food.eatFood()时可以绕过服务中的某些权限问题,基本上我不知道想实际呼叫food.eatFood(),而不是模拟food,以便我可以doNothing().when(food.eatFood())

我正在使用PowerMockito,我的代码如下:

@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
    }
}

运行测试时,food对象不是我想要的模拟对象,而是一个正在创建的真实对象,因此我无法告诉food.eatFood()doNothing()

我想念什么?

1 个答案:

答案 0 :(得分:0)

您可以使用PowerMockito的whenNew功能来拦截构造函数调用。

@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();
}