gpt4 book ai didi

java - JUnit:忽略方法调用

转载 作者:行者123 更新时间:2023-12-03 02:36:29 24 4
gpt4 key购买 nike

我知道使用 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());

Spying in Mockito

它是如何工作的:

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/

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