我知道使用 JUnit 可以使用 @Ignore 注释来忽略测试,但是如果从另一个方法调用该方法,是否可以忽略所有 JUnit 测试中的方法调用?
在下面的示例中,我希望能够测试 createPerson(...)
方法,但我希望我的测试忽略 createAddress(...)
方法
简单示例:Person.java
public void createPerson(...){
createAddress(...);
createBankAccount(...);
...
}
@IgnoreByTests
public void createAddress(...){
... creates address ...
}
public void createBankAccount(...)[
... creates bank account ...
}
最佳答案
在您的测试类中:
Person p = Mockito.spy(new Person());
它是如何工作的:
You can create spies of real objects. When you use the spy then the real methods are called (unless a method was stubbed). Real spies should be used carefully and occasionally, for example when dealing with legacy code.
Spying on real objects can be associated with "partial mocking" concept. Before the release 1.8, Mockito spies were not real partial mocks. The reason was we thought partial mock is a code smell. At some point we found legitimate use cases for partial mocks (3rd party interfaces, interim refactoring of legacy code, the full article is here)
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");
关于java - JUnit:忽略方法调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19383488/