unit-testing - 在 Racket 中模拟依赖行为

标签 unit-testing mocking racket

我刚开始在 Racket 中使用模拟,我想测试以下代码:

(define (tables #:connector [postgresql-connect postgresql-connect]
                     #:list-tables [list-tables list-tables])
  ; connect to the db
  (define pgc
    (postgresql-connect #:user "app_user"
                        #:database "test_database"
                        #:password "something_secure"))

  ; find all the tables
  (list-tables pgc))

所以我有几个测试用例:

(module+ test
  (require rackunit)
  (require mock)
  (require mock/rackunit)
  
  (test-case "it returns a report structure"
    (check-eq? (sniffer "not://a.url/test") "not://a.url/test"))
  (test-case "it calls the db connector with the right arguments"
    (define connector-mock (mock #:behavior postgresql-connect))
    (sniffer "not://a.url/test" #: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 postgresql-connect ))
    (define list-tables-mock (mock #:behavior list-tables ))
    
    (sniffer "not://a.url/test" #:connector connector-mock #:list-tables list-tables-mock)
    (check-mock-called-with? list-tables-mock (arguments connector-mock))))

当我运行测试时,我得到:

--------------------
it calls the db connector with the right arguments
; ERROR


tcp-connect: connection failed
  hostname: localhost
  port number: 5432
  system error: Connection refused; errno=61
--------------------
--------------------
it compiles a list of tables to examine
; ERROR


tcp-connect: connection failed
  hostname: localhost
  port number: 5432
  system error: Connection refused; errno=61
--------------------

这让我想到了这一点。我如何让模拟模拟 postgresql-connect 而无需调用实际实现?

最佳答案

当您使用 #:behavior 关键字时,您是在说 mock 实际上应该调用该函数。您正在传递 postgresql-connect,因此模拟实际上会尝试连接。您将需要传递一个不同的函数,该函数实际上并不进行连接但采用相同的参数,可能使用 mock 库中的 define-opaque

This example来自 mock 文档可能会有帮助。

关于unit-testing - 在 Racket 中模拟依赖行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68418796/

相关文章:

c++ - 创建一个接口(interface)来模拟 C++ 对象

unit-testing - 如何在docker-compose.yml中开始测试之前等待数据库迁移完成

c# - 测试 Linq 查询 EF 和存储库模式

unit-testing - Grails listOrder中单元测试中的@Mock域对象动态查找器抛出异常

scheme - 将多个函数一起重命名的宏

module - ( Racket ) "Cannot reference an identifier before its definition"带有从模块导入的标识符

unit-testing - 您可以在不创建测试代码的情况下执行单元/集成测试吗?

java - 调用 SimpleDateFormat 方法时模拟 Date()

c# - 使用 Rhino Mocks 模拟不可设置的子属性

namespaces - 使用 eval 评估 Racket 中的表达式