Java 如何模拟@Autowire对象的依赖关系?
我有一个@Autowire对象,其中的字段的方法调用需要模拟 在主要类别中:Java 如何模拟@Autowire对象的依赖关系?,java,spring,spring-boot,unit-testing,autowired,Java,Spring,Spring Boot,Unit Testing,Autowired,我有一个@Autowire对象,其中的字段的方法调用需要模拟 在主要类别中: @Component public class Pizza { private Tomato tomato; private Cheese cheese; @Autowired private Pizza(Tomato tomato, Cheese cheese) { this.tomato = tomato; this.cheese = che
@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中的番茄.createSauce()方法,但鉴于Pizza是自动连线的,我不确定如何实现。我是否必须在测试类中创建
tomato
和cheese
的Autowire实例?spring会自动知道将构造函数设置为这些实例吗?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);
}
}
因为这是标记为SpringBoot的,所以还值得指出@MockBean。(相关引用:“上下文中定义的任何相同类型的现有单个bean都将被mock替换。如果没有定义现有bean,将添加一个新的bean。”) 这意味着,在你的测试课上,你可以
@Autowired
私人披萨;
@蚕豆
私人番茄;
然后使用Mockito的
when
等你通常使用的方法。与另一个答案相比,这种方法为您节省了一两个注释(如果您正在模拟多个对象),以及对initMocks()的调用。对于Spring来说,@MockBean
注释是首选的解决方案:它将在Spring CDI上注册并注入Mockito模拟实例。使用@InjectMocks
注释,依赖项注入由Mockito完成,它在没有Spring的情况下也可以工作,但是测试设置需要更多的样板代码。