调试器在使用 Mockito 内联模拟制作器进行单元测试时突出显示错误的行使用 MockedStatic 模拟构造函数

问题描述

当使用 mockedstatic 和 mockedConstruction 时,我面临一个奇怪的行为。 调试器突出显示错误的行,但如果我添加了 System.out.println,我会看到代码正确执行。

这是代码

public class Example {


  private AnotherClass obj;
  
  public Example(Context context)
  {
    obj= new AnotherClass(context);
  }
  public static boolean isItValid(int num) {
    return (num > 5);

  }

  public static boolean matchesTheLimits(int num) {
    return (num > 100);
  }
  
  
  public void accepts(int num)
  {
    return isItValid(num) && matchesTheLimits(num) && obj.isItValidContext() ;
  }
}

我想测试接受方法,我在做这个单元测试时模拟上下文。

这里是单元测试的代码

@Test
public void testAccepts() {


  try (MockedConstruction<AnotherClass> mocked =
      Mockito.mockConstruction(AnotherClass.class,(mock,context) -> {

        when(mock.isItValidContext()).thenReturn(true);

      })) {

    try (MockedStatic<Example> mockedStatic =
        Mockito.mockStatic(Example.class)) {

      mockedStatic
          .when(() -> Example
              .isItValid( Mockito.anyInt()))
          .thenReturn(true);

      mockedStatic
      .when(() -> Example
          .matchesTheLimits( Mockito.anyInt()))
      .thenReturn(true);

      Example example = new Example(mockContext);

      boolean result = example.accepts(5);

      Assert.assertTrue(result);
    }
  }
}

我做错了什么吗?

非常感谢。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)