【问题标题】:How do I mock a method with void return type in JMockit?如何在 JMockit 中模拟具有 void 返回类型的方法?
【发布时间】:2014-08-12 09:08:40
【问题描述】:

我正在使用 TestNG 和 JMockit 进行测试。我的代码是这样的:

public boolean testMethod(String a, String b) {
   //processing .....
   mockClass.mockMethod(a);
   //processing....
}

mockMethod():

Class MockClass {
     public void mockMethod(String a) {
        //some operations to mock
     }
 }

我正在根据这个问题使用 MockUp:(How to mock public void method using jmockit?)

我仍在获取 NPE。我究竟做错了什么?还有,是因为我这样用吗?

@Test
public void test() {
   new Expectations() {
       {
       //for statements preceding mockMethod()....
       new MockUp<MockClass>(){
           @Mock
           public void mockMethod(String a) {
               //do nothing
           }
       };
       }
   };
 }

我把它放在 Expectations() 之外,也使用了 NonStrictExpectations。我该如何解决这个问题?

【问题讨论】:

  • 你从哪里得到 NPE?
  • 你应该为两个进程编写测试代码,所以你应该有两个方法。1- MockClass 2-测试在哪里调用 MockClass?

标签: java unit-testing testng jmockit


【解决方案1】:

如果要模拟的方法没有返回任何东西,你不需要做任何特殊的期望。您可以以通常的方式使用@Injectable 或@Mocked 注释定义要模拟的类。或者,您可以添加一个期望来验证该方法被调用的次数。您还可以添加验证步骤来捕获参数“a”并对其进行断言。请参考下面的代码示例。

@Tested
private MyClassToBeTested myClassToBeTested;
@Injectable
private MockClass mockClass;

@Test
public void test() {
    // Add required expectations
    new Expectations() {{
        ...
        ..
    }};

    // Invoke the method to be tested with test values;
    String expectedA = "testValueA";
    String expectedB = "testValueB";
    boolean result = myClassToBeTested.testMethod(expectedA, expectedB);

    // Assert the return value of the method
    Assert.assertTrue(result);

    // Do the verifications and assertions
    new Verifications() {{
        String actualA;
        mockClass.mockMethod(actualA = withCapture()); times = 1;
        Assert.assertNotNull("Should not be null", actualA);
        Assert.assertEquals(actualA, expectedA);
        ...
        ..
    }};

}

【讨论】:

    【解决方案2】:

    对于 void 方法的模拟,您可以在没有任何结果的情况下进行预期,如下所示:

    @Tested
    private MyClassToBeTested myClassToBeTested;
    
    @Injectable
    private MockClass mockClass;
    
    @Test
    public void test() {
    
        new Expectations() {{
            mockClass.mockMethod(anyString);
        }};
    
        String inputA = "testValueA";
        String inputB = "testValueB";
    
        boolean result = myClassToBeTested.testMethod(inputA, inputB);
    
        assertEquals(true, result);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-04
      • 1970-01-01
      • 1970-01-01
      • 2021-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-11
      相关资源
      最近更新 更多