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

Racket如何让Mock模拟postgresql-connect而不调用其实际实现?

问题原因

你创建mock时传入了#:behavior postgresql-connect,该参数的作用是指定mock被调用时执行的逻辑,你传入了真实的数据库连接函数,自然会触发真实的TCP连接请求,导致连接拒绝报错。

解决方法

你不需要让mock执行原函数的逻辑,只需要给它配置一个简单的返回逻辑,返回一个假的数据库连接对象即可,完全不会触发真实的数据库操作:

  • 用(const <返回值>)作为mock的行为,调用时会直接返回你指定的假值,不会执行任何原函数逻辑
  • 如果你不需要验证mock的返回值用途,返回任意假值都可以,比如符号'fake-connection、空值#f都可以

修改后的测试代码示例

(module+ test
  (require rackunit)
  (require mock)
  (require mock/rackunit)
  
  ;; 注意:你定义的业务函数名为tables,测试里调用的sniffer为笔误,这里统一修正为tables
  (test-case "it calls the db connector with the right arguments"
    ;; 配置mock调用时只返回假的连接对象,不执行真实连接逻辑
    (define connector-mock (mock #:behavior (const 'fake-pgc)))
    (tables #:connector connector-mock)
    (check-mock-called-with? connector-mock (arguments #:database "test_database"
                                                       #:password "something_secure"
                                                       #:user "app_user")))
  (test-case "it compiles a list of tables to examine"
    (define connector-mock (mock #:behavior (const 'fake-pgc)))
    (define list-tables-mock (mock #:behavior (const '())))
    
    (tables #:connector connector-mock #:list-tables list-tables-mock)
    (check-mock-called-with? list-tables-mock (arguments 'fake-pgc))))

补充说明

如果你的mock只需要验证调用参数,不需要后续代码使用它的返回值,也可以直接创建不带#:behavior参数的空白mock,调用时默认返回#<void>,不会执行任何额外逻辑。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 14:36:04