Java 如何在JMockit中模拟具有void返回类型的方法?

Java 如何在JMockit中模拟具有void返回类型的方法?,java,unit-testing,testng,jmockit,Java,Unit Testing,Testng,Jmockit,我正在使用TestNG和JMockit进行测试。我的代码是这样的: public boolean testMethod(String a, String b) { //processing ..... mockClass.mockMethod(a); //processing.... } mockMethod(): 我根据这个问题使用模型:() 我还在接受NPE。我做错了什么?还有,是因为我这样使用它吗 @Test public void test() { new Ex

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

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

我根据这个问题使用模型:()

我还在接受NPE。我做错了什么?还有,是因为我这样使用它吗

@Test
public void test() {
   new Expectations() {
       {
       //for statements preceding mockMethod()....
       new MockUp<MockClass>(){
           @Mock
           public void mockMethod(String a) {
               //do nothing
           }
       };
       }
   };
 }
@测试
公开无效测试(){
新期望(){
{
//对于mockMethod()前面的语句。。。。
新模型(){
@嘲弄
公共方法(字符串a){
//无所事事
}
};
}
};
}

我把它放在了预期之外()&也使用了非严格的预期。如何修复此问题?

如果要模拟的方法没有返回任何内容,则不需要在期望中执行任何特殊操作。您可以使用@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);
        ...
        ..
    }};

}

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

@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);
}

你从哪里得到NPE?你应该为两个进程编写测试代码,这样你应该有两个方法。1-MockClass 2-测试调用MockClass的位置?
@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);
}