我想编写一个测试来比较字符串的相等性。
以下是应该被测试的类的代码片段:
package ge.jibo.util;
public class TextManager {
private String concatenateTwoString(String t1, String t2) {
return t1 + t2;
}
public String concatenate(String t1, String t2) {
return concatenateTwoString(t1, t2);
}
}
下面是一个测试类:
package ge.jibo.util;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import static org.assertj.core.api.Assertions.assertThat;
public class TextManagerTest {
@Test
@PrepareForTest(TextManager.class)
void checkIfConcatenationWorks() throws Exception {
TextManager textmanager = PowerMockito.spy(new TextManager());
PowerMockito.doReturn("someText").when(textmanager,"concatenateTwoString", Mockito.anyString(), Mockito.anyString());
String text = textmanager.concatenate("ji","bo");
assertThat(text).isEqualTo("jibo");
}
}
如您所见,我想测试公共方法 concatenate
,该方法在同一类中调用私有方法 concatenateTwoString
。
我的想法是为私有方法创建一个模拟对象,每当它从公共方法被调用时,它应该返回常量值"someText"
。
但是从私有方法 concatenateTwoString
返回的是 null
而不是 "someText"
。
org.opentest4j.AssertionFailedError:
Expecting:
<null>
to be equal to:
<"jibo">
but was not.
Expected :jibo
Actual :null
有人知道如何修复吗?
依赖版本:
- junit-jupiter - 5.7.2
- junit-platform-launcher - 1.8.1
- mockito-core - 3.12.4
- mockito-junit-jupiter - 3.12.4
- powermock-core - 2.0.9
- powermock-api-mockito2 - 2.0.9