You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Java+Spock测试数据库无对应用户时的接口异常场景

Spock测试用户不存在异常场景的实现方案

核心修改点

你现有测试缺失了3个关键逻辑:

  • 没有给mock的userUrlRepository配置空返回值(模拟数据库查不到用户的场景)
  • then块的方法调用校验缺少参数匹配规则
  • 没有对接口返回的异常状态、错误信息做断言

完整测试代码

def "should throw an exception if user userId doesn't exist in database"(){
    given: "定义测试用户ID,且mock数据库返回空结果"
    String testUserId = "test123"
    1 * userUrlRepository.findById(UserId.userId(testUserId)) >> Optional.empty()

    when: "发起请求"
    def response = mvc.perform(get("/get/{userId}", testUserId)
            .contentType(MediaType.APPLICATION_JSON))
            .andDo(MockMvcResultHandlers.print())
            .andDo(docConfig())
            .andReturn()
            .response

    then: "验证异常返回结果"
    // 未配置全局异常处理器时Spring默认返回500状态码,如有自定义异常映射为404可修改为404
    response.status == 500
    // 验证响应中包含自定义的错误提示
    response.contentAsString.contains(String.format("user with id: %s doesn't exist", testUserId))
}

代码说明

  • given块里直接把mock交互和返回值写在一起,符合Spock的语法习惯,不需要拆分到then块单独写交互校验
  • 给findById加上参数匹配规则UserId.userId(testUserId),确保调用参数符合业务逻辑预期
  • 通过>> Optional.empty()指定mock方法的返回值,模拟数据库查不到用户的场景
  • 最终校验响应状态和错误信息,确保异常抛出逻辑符合预期

内容的提问来源于stack exchange,提问作者user9347049

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 02:15:03