【问题标题】:How to unit test a void returning method where the fields of the owning class are private and Spring @Autowired如何对拥有类的字段为私有且 Spring @Autowired 的 void 返回方法进行单元测试
【发布时间】:2016-10-17 19:16:05
【问题描述】:

我被赋予了对一个类进行单元测试的任务,其中它的字段被自动装配为 Spring bean。名为process 的主要公共方法不返回任何内容。这是该类的片段:

 public class AutoRejector{

    @Autowired
    private MNPServicesWrapper mnpWrapper;
    //some more autowired fields

    public void process() {
        List<RequestInfo> requests = mnpWrapper.getNewMnpRequests();
        ........
    }
 }

MNPServicesWrapper 是一个接口。在测试期间,我想提供我自己的测试实现,它会在调用getNewMnpRequests 方法时返回一些测试值。

如果我能够通过构造函数或设置器设置此字段,那将是直截了当的。但是如何设置@Autowired 字段呢?

【问题讨论】:

  • 了解模拟

标签: junit4 private-members spring-bean jmock


【解决方案1】:

您可以使用 Mockito 和 PowerMock 等模拟框架。它们有助于将模拟对象注入您的测试类。然后,您可以指定方法返回。 (他们使用反射来注入测试对象。您可以通过使用反射而不使用 Mockito 来做同样的事情) 对于您的 void 方法,您可以断言使用这些模拟框架之一调用 mnpWrapper.getNewMnpRequests() 的次数。

请进一步了解 Mockito,导入 JAR 并在您的 JAVA 项目中使用。

您在 Mockito 中的代码测试示例是:

  @RunWith(MockitoJUnitRunner.class)
  public class AutoRejectorTest {
    @Mock
    MNPServicesWrapper mnpWrapper;

    @InjectMocks
    AutoRejector autoRejector;

    @Test
    public void processTest(){
       autoRejector.process();
       //Assert that the getNewMnpRequests method was called exactly once
       Mockito.verify(mnpWrapper,times(1)).getNewMnpRequests();
      }
}

【讨论】:

    猜你喜欢
    • 2011-06-25
    • 2014-05-10
    • 2018-02-01
    • 2019-11-17
    • 2010-09-20
    • 1970-01-01
    • 2016-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多