我是java,单元测试和mockito的新手,但我想从我的班级测试一些东西。
我要测试的课程:
abstract class Irc {
Command received(String data) {
// parsing
receivedCommand(prefix, command, parameters, trailing, tags);
return new Command(prefix, command, parameters, trailing, tags);
}
private void receivedCommand(String prefix, String command, String[] parameters, String trailing, Map<String, String> tags) {
String nick = getNickFromPrefix(prefix);
parsed(prefix, command, parameters, trailing);
if (command.equals("MODE")) {
if (parameters.length == 3) {
String chan = parameters[0];
String mode = parameters[1];
String name = parameters[2];
if (mode.length() == 2) {
String modeChar = mode.substring(1, 2);
if (mode.startsWith("+")) {
onModeChange(chan, name, true, modeChar, prefix);
} else if (mode.startsWith("-")) {
onModeChange(chan, name, false, modeChar, prefix);
}
}
}
return;
}
}
void onModeChange(String channel, String nick, boolean modeAdded, String mode, String prefix) {
}
}
修改
我想确保在onModeChange
被调用后调用received
。
到目前为止我所拥有的:
@Test
public void modeChangeReceivedRightSyntax() {
try {
irc = new Irc("Test") {
@Override
public void debug(String line) {
System.err.println(line);
}
@Override
void onModeChange(String channel, String nick, boolean modeAdded, String mode, String prefix) {
System.out.println("Mode Change: " + channel + " " + nick + " " + mode + " " + prefix + " " + modeAdded);
}
};
ircMock = spy(irc);
when(
ircMock.received(":jtv MODE #channel +o user")
).thenReturn(
new Command("jtv", "MODE", new String[]{"#channel", "+o", "user"}, "", null)
);
verify(ircMock).onModeChange("#channel", "user", true, "o", "jtv");
} catch (Exception ex) {
fail("Exception: " + ex.toString());
}
}
when
正在运行,但verify
失败且Actually, there were zero interactions with this mock.
答案 0 :(得分:2)
您的代码未调用任何业务方法。它只会模拟接收到的方法应该如何表现,但实际上并没有调用该方法。 由于您的Irc类是抽象的,因此您使用间谍的方法很好,但您不应该模拟接收的方法,而是告诉间谍委派给真正的方法。然后你可以验证是否调用了onModeChange。
Irc irc = spy(Irc.class, withSettings().defaultAnswer(CALLS_REAL_METHODS));
// Business method
irc.received(":jtv MODE #channel +o user");
// Asserts
verify(irc).onModeChange("#channel", "user", true, "o", "jtv");