我试图测试域对象中的一些方法,代码似乎执行(基于日志),但断言失败。
正在测试的代码(**extendDates**),正在工作,我现在只是添加单元测试。--我假设我在mocking.The中做错了什么--下面是我的代码的简化版本。根据日志输出,应该传递断言。
class EventDate{
Date startDate
Date endDate
belongsTo = [Appointments owner]
static constraints = {
endDate(nullable:true, blank:false)
startDate(nullable:false, blank:false)
}
}
class Appointments {
hasMany = [ eventDates: EventDate]
belongsTo = [ customer: Customer ]
def extendDates(start,end){
//some logic on eventDates...
EventDate(startDate:start,endDate:end, owner:this).save(flush:true,failOnError:true);
}
}
@TestFor(Appointments)
@Mock([EventDate])
class AppointmentsTests {
void testDateExtend(){
assertTrue domain != null
assertTrue domain instanceof Appointments
//Log indicates the correct execution and creation of event
domain.extendDates(new Date(),null)
//following returns NullPointerException
assertTrue domain.eventDates.size() == 1
}
}发布于 2015-05-22 13:15:51
是的,您将获得NullPointerException在assert条件下。原因是,您正在extendDates方法中创建extendDates实例,但实际上并没有将它添加到Appointments域中的eventDates列表中。
因此,您必须修改该方法,如下所示:
// Initialize with empty array to avoid NPE
List<EventDate> eventDates = []
static hasMany = [ eventDates: EventDate]
def extendDates(start, end) {
EventDate instance = EventDate(start, end).save()
// And add it to the list of events
this.addToEventDates(instance)
this.save(flush: true)
}现在,您的测试用例应该运行您的断言条件。
(而且,看起来您没有在end中添加可空约束,但是在创建EventDate实例时传递空值,可能不包括在示例代码中)
发布于 2015-05-22 13:16:39
在您的示例中,您要测试
if (create_new)变量"create_new“永远不会设置,因此将使用groovy逻辑测试false,因此永远不会执行if语句。
if语句从不向约会的"eventDates“属性添加任何内容,这也意味着断言将失败。
我认为你的例子是不完整的,因此在你扩大它之前是帮不了你的。
https://stackoverflow.com/questions/30395676
复制相似问题