【问题标题】:Testing a boolean being returned by inner method测试内部方法返回的布尔值
【发布时间】:2021-01-15 22:24:52
【问题描述】:

我需要测试当我用'hello'调用Myfunction时checkIt函数返回的布尔值是否应该返回true。

public class Myclass 
{
    public void Myfunction(x)
       {

        if(x!= null) 
        {
        boolean containsHello;
        containsHello = checkIt(x) 
        }

        Rest of the statements for Myfunction  ------- 
        goes here -------
    }

     @VisibleForTesting
     boolean checkIt(String x)
     {
      return x.contains('hello');
     }

当我将“hello”传递给 Mockito 中的 Myfunction 时,我想对 checkIt 函数是否返回 true 进行单元测试。我尝试了下面的代码,但它似乎不起作用


String loc = Mockito.spy('hello');
        Mockito.verify(Myclass).checkIt(x);
        Assert.assertEquals(true, checkIt(loc));

【问题讨论】:

  • 这里不需要 Mockito。您的代码只是检查某个字符串是否出现在传入的值中。如果您尝试验证与变量的某种交互,则需要 Mockito。
  • 您能否详细展示一个有关实施的示例?

标签: java unit-testing testing mockito powermockito


【解决方案1】:

正如 cwa 所提到的,您不需要创建间谍 - 只需直接使用字符串即可。此外,在 Java 中,您需要对 Java 中的字符串使用双引号。这看起来像:

Assert.assertEquals(true, checkIt("some string"));

【讨论】:

    猜你喜欢
    • 2012-11-03
    • 1970-01-01
    • 2015-09-10
    • 1970-01-01
    • 2012-11-04
    • 2015-06-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多