gpt4 book ai didi

grails - 无法模拟服务的返回值

转载 作者:行者123 更新时间:2023-12-02 16:01:06 25 4
gpt4 key购买 nike

我有一个 Controller 测试问题。我尝试模拟服务方法的返回值,但它不返回特定对象,无论如何都不会调用服务方法。
测试方法:

def "shouldReturnStatus"() {
given:
controller.repairService.getRepair('123465') >> repair;
when:
controller.status();
then:
response.text == '{"currentStatus":"Repair was found.","repairFound":true}'
}

修复模拟在setup方法中声明。

Controller 方法:
def status() {      
String repairCode = params.repairCode;
if(repairCode == null || repairCode.isEmpty()) {
log.info("REPARATURSTATUSABFRAGE: Reparaturcode wurde nicht angegeben")
renderEmptyRepairCode();
} else if(repairService.getRepair(repairCode)) {
Repair repair = repairService.getRepair(repairCode);
if(repair) {
log.info("REPARATURSTATUSABFRAGE: Reparaturstatus mit Code " + repairCode + " erfolgreich ausgegeben.")
Customer customer = repair.getCustomer();
renderRepairStatus(repair, customer);
}
} else {
log.info("REPARATURSTATUSABFRAGE: Reparatur mit Code " + repairCode + " nicht gefunden.")
renderRepairNotFound(repairCode);
}
}

repairService-Method:
def getRepair(String repairCode) {      
Repair repair = Repair.findByRepairCode(repairCode);
if(repair == null) {
String upperCaseRepairCode = repairCode.toUpperCase();
repair = Repair.findByRepairCode(upperCaseRepairCode);
}
return repair;
}

我在setup-Method中 mock 了repairService
repairService = Mock(RepairService);

我认为服务方法的代码并不重要,因为我 mock 了该方法的返回值。还是我听错了?

最佳答案

您需要修改测试:

def "shouldReturnStatus"() {
given:
controller.repairService = Mock(RepairService)
controller.repairService.getRepair('123465') >> repair

when:
controller.status();
then:
response.text == '{"currentStatus":"Repair was found.","repairFound":true}'
}

如果我的解释正确,那么您已经在Spec内创建了一个Mock(RepairService)类型的实例变量。这并不意味着您的 Controller 将使用此模拟服务。您实际上需要将其分配给 Controller 。

关于grails - 无法模拟服务的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30681823/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com