2

I know using JUnit that it is possible to ignore a test using the @Ignore annotation but is it possible to ignore a method call from all JUnit tests if the method is called from another method?

In the example below i want to be able to test the createPerson(...) method but i want my test to ignore the createAddress(...) method

Quick Example : Person.java

public void createPerson(...){
    createAddress(...);
    createBankAccount(...);
    ...
}

@IgnoreByTests
public void createAddress(...){
... creates address ...
}

public void createBankAccount(...)[
... creates bank account ...
}
4

2 回答 2

6

在您的测试课程中:

Person p = Mockito.spy(new Person());

在 Mockito 中进行间谍活动

这是如何运作的:

您可以创建真实对象的间谍。当您使用 spy 时,会调用真正的方法(除非方法被存根)。真正的间谍应该小心谨慎地偶尔使用,例如在处理遗留代码时。

监视真实对象可能与“部分模拟”概念相关联。在 1.8 版本之前,Mockito 间谍不是真正的部分模拟。原因是我们认为部分模拟是代码异味。在某些时候,我们发现了部分模拟的合法用例(第 3 方接口,遗留代码的临时重构,完整的文章在 这里

   List list = new LinkedList();
   List spy = spy(list);

   //optionally, you can stub out some methods:
   when(spy.size()).thenReturn(100);

   //using the spy calls real methods
   spy.add("one");
   spy.add("two");

   //prints "one" - the first element of a list
   System.out.println(spy.get(0));

   //size() method was stubbed - 100 is printed
   System.out.println(spy.size());

   //optionally, you can verify
   verify(spy).add("one");
   verify(spy).add("two");
于 2013-10-15T14:20:28.767 回答
0

这就是嘲讽出现的时候。例如,Mockito:

class Tests {
 private Mock<MyClass> mockedClass;
 @Setup
 void Setup(){
  mockedClass = new Mock<MyClass>();
 }

 @Test
 void MyMockedTest(){
  Mockito.when(mockedClass.createAddress()).thenReturn("Some address 15, USA");
 }
}
于 2013-10-15T14:20:09.373 回答