实例 void 方法的模拟无需调用 'expectLastCall' 方法即可工作

mocking of instance void method is working without calling 'expectLastCall' method

我刚刚编写了示例测试用例,我想在其中模拟一个 void 实例方法。我很惊讶,我的测试用例没有调用 expectLastCall 方法就通过了。我想知道,在模拟实例 void 方法时是否不需要调用 expectLastCall?

StringUtil.java

package com.sample.util;

import com.sample.model.MethodNotImplementedException;

public class StringUtil {
    public String toUpperAndRepeatStringTwice(String str) {
        String upperCase = str.toUpperCase();
        sendStringToLogger(upperCase);
        return upperCase + upperCase;
    }

    public void sendStringToLogger(String str){
        throw new MethodNotImplementedException();
    }
}

StringUtilTest.java

package com.sample.util;

import static org.junit.Assert.assertEquals;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.easymock.PowerMock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest({ StringUtil.class })
public class StringUtilTest {

    @Test
    public void toUpperAndRepeatStringTwice() {
        StringUtil stringUtil = PowerMock.createPartialMock(StringUtil.class, "sendStringToLogger");

        String str = "HELLO PTR";
        stringUtil.sendStringToLogger(str);
        //PowerMock.expectLastCall().times(1);
        PowerMock.replayAll();

        String result = stringUtil.toUpperAndRepeatStringTwice("hello ptr");

        assertEquals(result, "HELLO PTRHELLO PTR");
    }
}

expectLastCall 不是必需的。对于 EasyMock 和 PowerMock 层也是如此。所以你是对的。

它是为了让一些用户清楚。因为它很明显之前的方法是一个期望而不是一些随机调用。但这更多的是风格问题而不是要求。

您也不需要 time(1),因为它是默认值。

顺便说一句,答案here是错误的,我已经相应地对其进行了评论。