void 方法的模拟参数
Mocking parameter of a void method
假设我有以下 setter:
public void setNewPath(final String path) {
if (StringUtils.hasText(path) && !path.endsWith(File.separator)) {
this.newPath = path + File.separator;
} else {
this.newPath = path;
}
}
我想在我的测试方法中模拟参数 path
。这可能吗?
这不是模拟的好问题。在任何情况下都不会就地修改参数,因为字符串是不可变的,尽管模拟可以告诉您是否调用了方法,但它不会让您跟踪您将要进行的修改的值。
正如 Brian Agnew 在评论中发布的那样,"test the method with various inputs, and assert some behaviour (e.g. the setting of newPath)"。确保 newPath
有一个 getter,即使 getter 仅用于测试(并记录在案)。
假设我有以下 setter:
public void setNewPath(final String path) {
if (StringUtils.hasText(path) && !path.endsWith(File.separator)) {
this.newPath = path + File.separator;
} else {
this.newPath = path;
}
}
我想在我的测试方法中模拟参数 path
。这可能吗?
这不是模拟的好问题。在任何情况下都不会就地修改参数,因为字符串是不可变的,尽管模拟可以告诉您是否调用了方法,但它不会让您跟踪您将要进行的修改的值。
正如 Brian Agnew 在评论中发布的那样,"test the method with various inputs, and assert some behaviour (e.g. the setting of newPath)"。确保 newPath
有一个 getter,即使 getter 仅用于测试(并记录在案)。