gpt4 book ai didi

java - 如何模拟来自 jar (JAVA) 的类中的方法

转载 作者:行者123 更新时间:2023-11-30 06:19:24 24 4
gpt4 key购买 nike

我无法解决上周一直困扰我的问题。

可以模拟一个位于 jar 内的类,这样我就不会调用真正的方法。

示例:

3 Classes (Class Person, Class PersonTest, Class PersonExternalJar)

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.
}
}

As I understood about unit testing it is to isolate the class and try its behaviour without calling external methods (that's why I use mockito).

Mockito 核心版本 1.10.19Junit 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 方法而不是构造函数:

public class Person {
private PersonalExternalJar pej;

setPersonalExternalJar(PersonalExternalJar pej) {
this.pej = pej;
}
}

关于java - 如何模拟来自 jar (JAVA) 的类中的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48510471/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com