我无法解决上周一直困扰我的问题。
可以模拟一个类,它在罐子里,所以我不调用真正的方法。
例:
3 类(类人、类人测试、类人外部罐(
public class Person{ private PersonalExternalJar pej; public void methodA(){ *do some stuff* pej = new PersonalExternalJar(); ArrayList people = pej.doSomething(AnyString,AnyString,AnyObject); *do some stuff* People2 p = new People2(); // This class it is somewhere in my project lets say String SomePeople = p.doSomeStuff(); } } @RunWith(MockitoJUnitRunner.class) public class PersonTest{ @Mock private People2 p; @Mock private PersonExtenarlJar pej; // I get an error like I can't find this class or some internal thing of this class. @InjectMocks private Person pr; @Test public void personTest(){ *do some stuff* pr = new Personal(); //try both declare the class and not declaring the class //when I do the next Mockito.doReturn("anything").when(p).doSomeStuff(); // WORKS Mockito.doReturn(AnyArray).when(pej).doSomething(AnyString,AnyString,AnyObject) // CAN'T DO THIS //Doesn't work //Alternatively I tried to take off the annotation mock and do the following. PersonalExternalJar pej = Mockito.mock(PersonalExternalJar.class) //Still doesn't work. } }
正如我对单元测试的理解,它是隔离类并在不调用外部方法的情况下尝试其行为(这就是我使用 mockito 的原因(。
莫米托核心版本 1.10.19朱尼特 4.12.
我希望有人能给我一个解决方案,或者让我看到另一个角度,或者让我明白我可能对概念感到困惑。
您需要
在Person
类中使用PersonalExternalJar
公开依赖项来模拟它。一种方法是使用构造函数。
因此,将Person
类重构为如下所示:
public class Person {
private final PersonalExternalJar pej;
public Person (PersonalExternalJar pej) {
this.pej = pej;
}
public void methodA(){
*do some stuff*
ArrayList people = pej.doSomething(AnyString,AnyString,AnyObject);
*do some stuff*
People2 p = new People2(); // This class it is somewhere in my project lets say
String SomePeople = p.doSomeStuff();
}
}
在应用程序代码中:
new Person(new PersonalExternalJar());
在您的测试中:
PersonalExternalJar pejMocked = mock(PersonalExternalJar.class);
new Person(pejMocked);
您还可以选择使用 set
方法代替 constructor
:
public class Person {
private PersonalExternalJar pej;
setPersonalExternalJar(PersonalExternalJar pej) {
this.pej = pej;
}
}