如何从类中模拟一个方法,它来自jar(JAVA)

时间:2018-01-29 21:43:35

标签: java unit-testing mockito junit4

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

可以模拟一个类在jar中的类,所以我不会调用真正的方法。

示例:

  

3个类(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.
     }
}
     

正如我对单元测试的理解,它是隔离类并在不调用外部方法的情况下尝试其行为(这就是我使用mockito的原因)。

Mockito核心版本1.10.19 Junit 4.12。

我希望有人可以给我一个解决方案,或让我看到另一个观点,或让我明白我可能会对概念感到困惑。

1 个答案:

答案 0 :(得分:1)

您需要在PersonalExternalJar类中使用Person公开依赖项来模拟它。一种方法是使用构造函数。

所以重构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;
     }
}