代码之家  ›  专栏  ›  技术社区  ›  robertpostill

模仿racket中的依赖行为

  •  0
  • robertpostill  · 技术社区  · 3 年前

    我刚刚开始在racket中使用Mock,我想测试以下代码:

    (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 不调用实际的实现?

    0 回复  |  直到 3 年前
        1
  •  1
  •   Sam Tobin-Hochstadt    3 年前

    当你使用 #:behavior 关键字,你是说mock应该调用这个函数。你通过了 postgresql-connect ,所以mock实际上试图连接。您将需要传递一个不同的函数,该函数实际上不进行连接,但采用相同的参数,可能是 define-opaque mock 图书馆

    This example 嘲弄 文档可能会有所帮助。