【问题标题】:Could not mock return value of service无法模拟服务的返回值
【发布时间】:2015-06-06 23:32:00
【问题描述】:

我的控制器测试有问题。我尝试模拟服务方法的返回值,但它不返回特定对象并调用服务方法。 测试方法:

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

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

控制器方法:

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-方法:

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

我在 setup-Method 中模拟了 repairService

repairService = Mock(RepairService);

我认为服务方法的代码并不重要,因为我模拟了这个方法的返回值。还是我理解错了?

【问题讨论】:

    标签: grails spock


    【解决方案1】:

    你需要修改你的测试:

    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) 类型的实例变量。这并不意味着您的控制器将使用此模拟服务。您需要将其实际分配给控制器。

    【讨论】:

      猜你喜欢
      • 2015-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-28
      • 2021-12-02
      • 2013-01-31
      • 1970-01-01
      相关资源
      最近更新 更多