我有这样的东西:
public class Class1 {
@Autowired
Class2 class2;
public Object class1Method {
// Do something
Object obj = class2.class2Method(arg);
// Do something with obj
return somthing;
}
}
我正在对 Class1 进行单元测试,我想模拟 class2Method。我尝试寻找解决方案,结果发现:
Test class with a new() call in it with Mockito
我知道如果我在 class1Method 中创建 Class2 的新实例,这个解决方案就可以工作,但在我的例子中,我使用 Spring 依赖注入(inject),但我不知道如何做到这一点。
最佳答案
根据你如何使用 spring 构建 DI,如果你在字段上有 @Autowired
,你可以使用类似的东西
@RunWith(SpringRunner.class)
public Class1Test {
@InjectMocks
@Autwired
private Class1 class1;
@Mock
Class2 class2;
@BeforeMethod
public void initMocks(){
MockitoAnnotations.initMocks(this);
}
@Test
public Object testClass1Method {
when(class2.class2Method(anyString()).thenReturn(expectedReturn);
//Now test whatever you need with mocked class2.class2Method
}
}
如果您有构造函数 DI(构造函数上的 @Autowired
),则更容易,并且不需要为测试提供 spring 上下文
public Class1Test {
private Class1 class1;
private Class2 class2;
@BeforeMethod
public void initMocks(){
class2 = mock(Class2.class);
class1 = new Class1(class2);
}
//then use the same approach to mock any methods that you need
}
关于java - 使用Spring依赖注入(inject)时如何模拟在其他方法中调用的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42693486/