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



在我的一个跑步类中,我有:

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

我的食物造物班是这样:

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

我的食物因面是:

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()

我缺少什么?

您可以使用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();
}

相关内容

  • 没有找到相关文章

最新更新