使用 Mockito 模拟方法的局部变量

Using Mockito to mock a local variable of a method(使用 Mockito 模拟方法的局部变量)
本文介绍了使用 Mockito 模拟方法的局部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我有一个需要测试的类A.以下是A的定义:

I have a class A that needs to the tested. The following is the definition of A:

public class A {
    public void methodOne(int argument) {
        //some operations
        methodTwo(int argument);
        //some operations
    }

    private void methodTwo(int argument) {
        DateTime dateTime = new DateTime();
        //use dateTime to perform some operations
    }
}

并且基于 dateTime 值,一些数据将被操作,从数据库中检索.对于此数据库,这些值通过 JSON 文件进行持久化.

And based on the dateTime value some data is to be manipulated, retrieved from the database. For this database, the values are persisted via a JSON file.

这使事情变得复杂.我需要的是在测试时将 dateTime 设置为某个特定日期.有没有办法可以使用 mockito 模拟局部变量的值?

This complicates things. What I need is to set the dateTime to some specific date while it is being tested. Is there a way I can mock a local variable's value using mockito?

推荐答案

你不能模拟一个局部变量.但是,您可以做的是将其创建提取到 protected 方法并 spy 它:

You cannot mock a local variable. What you could do, however, is extract its creation to a protected method and spy it:

public class A {
  public void methodOne(int argument) {
    //some operations
    methodTwo(int argument);
    //some operations
  }

  private void methodTwo(int argument) {
    DateTime dateTime = createDateTime();
    //use dateTime to perform some operations
  }

  protected DateTime createDateTime() {
    return new DateTime();
  }
}

public class ATest {
  @Test
  public void testMethodOne() {
    DateTime dt = new DateTime (/* some known parameters... */);
    A a = Mockito.spy(new A());
    doReturn(dt).when(a).createDateTime();
    int arg = 0; // Or some meaningful value...
    a.methodOne(arg);
    // assert the result
}

这篇关于使用 Mockito 模拟方法的局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How to send data to COM PORT using JAVA?(如何使用 JAVA 向 COM PORT 发送数据?)
How to make a report page direction to change to quot;rtlquot;?(如何使报表页面方向更改为“rtl?)
Use cyrillic .properties file in eclipse project(在 Eclipse 项目中使用西里尔文 .properties 文件)
Is there any way to detect an RTL language in Java?(有没有办法在 Java 中检测 RTL 语言?)
How to load resource bundle messages from DB in Java?(如何在 Java 中从 DB 加载资源包消息?)
How do I change the default locale settings in Java to make them consistent?(如何更改 Java 中的默认语言环境设置以使其保持一致?)