这里我试图监视一个方法,因为它从外部调用了另一个方法。我所需要的只是模拟外部方法。下面是我对项目类型的遗留项目的模拟
sub-query
这是我的测试用例
public class TestClass {
public int dependencyOne(){
System.out.println("Need to mock Externally ");
return 100;
}
public int methodNeedTobeTested(int a){
int c = new AnotherClass().dependencyTwo();
return a + this.dependencyOne() + c;
}
}
public class AnotherClass {
public int dependencyTwo(){
System.out.println("Need to mock externally");
return 100;
}
}
我的输出:
需要在外部进行模拟
java.lang.AssertionError: 预期:30 实际:120
缺少什么?
依赖性:
public class TestClassTest {
@InjectMocks
TestClass testClass;
@Mock
AnotherClass anotherClass;
@Before
public void init() {
MockitoAnnotations.initMocks(this);
}
@Rule
public MockitoRule initRule = MockitoJUnit.rule();
@Test
public void methodNeedTobeTested() {
testClass = Mockito.spy(new TestClass());
Mockito.when(anotherClass.dependencyTwo()).thenReturn(10);
Mockito.doReturn(10).when(testClass).dependencyOne();
assertEquals(testClass.methodNeedTobeTested(10),30);
}
}
答案 0 :(得分:1)
要模拟对AnotherClass
的调用,请勿在应用程序代码中使用new
创建实例。这将始终实例化 real 对象,而您将无法对其进行模拟。
更好的方法是将AnotherClass
的实例作为TestClass
的构造函数的一部分,并遵循控制权的反转(例如,使用CDI的Spring Framework进行依赖注入)。
public class TestClass {
public AnotherClass anotherClass;
public TestClass(AnotherClass anotherClass) {
this.anotherClass = anotherClass;
}
public int dependencyOne(){
System.out.println("Need to mock Externally ");
return 100;
}
public int methodNeedTobeTested(int a){
int c = anotherClass.dependencyTwo();
return a + this.dependencyOne() + c;
}
}
使用这种方法,您的测试应该可以进行。