我有一个@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()方法,但我不确定如何做到这一点,因为披萨是自动连接的。我必须在测试类中创建tomato和cheese的自动绑定实例吗?spring会自动知道将构造函数设置为这些实例吗?
发布于 2020-09-08 08:57:06
Mockito提供了@Mock注解来模拟对象,并提供了@InjectMocks注解来将这些注解注入到自动连接字段中。
@RunWith(SpringRunner.class)
@ExtendWith(MockitoExtension.class)
public class TestPizza {
@Mock
private Tomato tomato;
@Mock
private Cheese cheese;
@InjectMocks
private Pizza pizza;
@BeforeEach
void init() {
MockitoAnnotations.initMocks(this);
when(tomato.createSauce()).thenReturn("Spicy Sauce");
}
@Test
private void testCreatePizza {
pizza.createPizza(tomato, cheese);
}
}发布于 2020-09-08 21:36:57
因为它被标记为spring-boot,所以还有必要指出@MockBean annotation。(相关引用:“任何在上下文中定义的相同类型的现有单个bean都将被mock替换。如果没有定义现有bean,将添加一个新bean。”)
这意味着,在测试类中,您可以执行以下操作
@Autowired
private Pizza pizza;
@MockBean
private Tomato tomato;然后像往常一样使用Mockito的when。与其他答案相比,这种方法节省了一两个注释(如果您模拟多个事物),以及对initMocks()的调用。
https://stackoverflow.com/questions/63785593
复制相似问题