【发布时间】:2020-09-08 00:11:36
【问题描述】:
我有一个 @Autowire 对象,其中包含需要模拟其方法调用的字段。
在主类中:
@Component
public class Pizza {
private Tomato tomato;
private Cheese cheese;
@Autowired
private Pizza(Tomato tomato, Cheese cheese) {
this.tomato = tomato;
this.cheese = cheese;
}
public String arrangePizza(tomato, cheese) {
Sauce sauce = tomato.createSauce();
combine(sauce, cheese);
return "Pizza created!"
}
}
在测试类中:
@RunWith(SpringRunner.class)
public class TestPizza {
@Autowire
private Pizza pizza;
//probably create instances of cheese and tomato here?
private void testCreatePizza {
//here I want to mock tomato.createSauce()
pizza.arrangePizza(tomato, cheese);
}
}
我正在尝试使用 Mockito 或 EasyMock 在 testCreatePizza 中模拟方法tomato.createSauce(),但鉴于 Pizza 是自动装配的,我不确定如何执行此操作。我是否必须在测试类中创建 tomato 和 cheese 的 Autowire 实例? spring 会自动知道将构造函数设置为那些实例吗?
【问题讨论】:
标签: java spring spring-boot unit-testing autowired