我有一个匹配两个对象的方法。如果第一个对象的每个属性与第二个对象的属性匹配,则会发生匹配。我知道在Groovy中我可以遍历一个对象的字段来执行此操作。问题是我得到了一个我无法弄清楚的异常。
在代码中:
方法:private match(Project projectToMatch, Project project)
项目类:
class Project
{
final String name
final Person techLead
}
我想做类似的事情:
private boolean match(Project projectManaged, Project project) {
project.properties.each { prop, value ->
if(value != projectManaged["$prop"] {
return false
}
}
return true
}
但我得到了:
java.lang.AssertionError: Closure com.gustavo.tribal.ProjectManagerImplTest$_testEditProjectShouldNotEditIfPriorityAlreadyExists_closure3@32da5a84
should have failed with an exception of type com.gustavo.tribal.exceptions.WrongProjectException,
instead got Exception java.lang.NullPointerException: Cannot invoke method call() on null object
两个参数都不为null,但techLead的值适用于两者。我确信null值和异常之间存在关系,但我无法做到。
修改:
测试是:
void testEditProjectShouldNotEditIfPriorityAlreadyExists() {
projectManagerImpl.addProject(project)
projectManagerImpl.addProject(project2)
def msg = shouldFail(WrongProjectException) {
projectManagerImpl.editProject(project, project2b)
}
assertEquals "Can't edit project as the requested priority (" + project2b.priority + ") is already in use", msg
}
editProject
的代码:
void editProject(Project project, Project editedProject) {
for(Project projectManaged : allProjects) {
if(match(projectManaged, project)) {
if(projectManaged.priority != editedProject.priority && usedPriorities.get(editedProject.priority)) {
throw new WrongProjectException("Can't edit project as the requested priority (" + editedProject.priority + ") is already in use")
}
removeProject(project)
addProject(editedProject)
}
}
}
答案 0 :(得分:0)
事实证明我在match
方法中缺少一个括号。另外,我应该使用projectManaged["$prop"]
projectManaged[prop]