java - JUnit:忽略方法调用

标签 java unit-testing junit

我知道使用 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/

相关文章:

java try catch finally - 返回

java - Eclipse java 中出现包不存在的错误 [ERROR]

node.js - 使用 Jest(和 mockgoose)测试 Node.js API

c++ - 在同一个函数/程序中使用 WebSocket++ 服务器和客户端

android - 如何将 TestNG 与 Robolectric 一起使用?

java - Morphia 泛型 - 不可能吗?

java - AsyncTask 在 fragment 显示后更新数据

php - Laravel phpunit 拒绝用户访问

java - 如何从 java 中收集 JVM 性能统计信息

java - 如何在JUnit4中使用ClassRule启动Spring Boot服务器?