首页 > 解决方案 > 无法在java中的方法内模拟局部变量

问题描述

我是测试新手,使用 mockito 和 junit 进行测试。类和测试方法看起来像这样。编辑:对方法进行了更正。

class SomeClass
{

   Data data;
   public Data method1(int n1, int n2)
   {

        data = method2(n1, n2);

        if (data != null && data.something()!=null  && !data.something().isEmpty()) 
        {
          // other instructions
        }
        return data;
   }
   Data method2(int n1, int n2)
   {
       Data data1 = Some calculations;
       return data;
   }
}

//Test class


@Mock
Data data;


@Test
public void testData()
{
    @Test 
    public void getReceivingDataTest() 
    {
        
        SomeClass mock = Mockito.spy(new SomeClass.class);
        when(mock.method2(1,1)).thenReturn(data);
        mock.method1(1,1);
    }
}

在这里,我试图从测试方法中设置从 method2 接收到的数据的值,但不幸的是我无法模拟局部变量Data data。它调用真正的方法method2并获得一个空值并抛出一个空异常。我曾尝试使用模拟而不是间谍,但我得到了同样的错误。我该怎么办?编辑:method2() 正在调用另一个服务,因为我模拟了它,所以总是返回 null,并且不会执行 method1() 中的“其他指令”。

标签: junitmockito

解决方案


推荐阅读