如何对阶乘函数中的堆栈溢出进行单元测试?

How can I unit test for a stack overflow in my factorial function?

我在 Racket 中创建了一个阶乘函数,需要对其进行单元测试以传递一个非常大的数字,从而捕获溢出异常。如果捕获到异常,则测试应该通过,反之亦然。这是我的代码。

#lang racket

(provide recursive_factorial)
(provide tail_factorial)


(define (recursive_factorial number)
 (cond [(= 0 number) 1]
       [(negative? number) (raise-argument-error 'recursive_factorial "negative?" number)]
       [(*  number (recursive_factorial (- number 1)))]))


(define (tail_factorial number accumulator)

 (cond[( = number 0 ) accumulator]
      [(negative? number) accumulator (raise-argument-error 'tail_factorial  "negative?" number accumulator)]
      [(tail_factorial (- number 1) (* accumulator number ))]
      ))

这是我尝试对其进行单元测试的尝试。

(check-not-exn (λ () (recursive_factorial(100000000)))"stack overflow")
 (check-not-exn (λ () (tail_factorial(100000000)))"stack overflow")

在很多帮助下,我能够在负面条件下工作。任何帮助表示赞赏。

number 为负时,您的函数 returns -1。那么测试不应该是:

(check-equal? (recursive_factorial -4) -1)

更新

怎么样:

 #lang racket
 (provide recursive_factorial)
 (define (recursive_factorial number)
  (cond [(= 0 number)       1]
        [(negative? number) (error 'recursive_factorial
                                   "Cannot pass a negative number")]
        [else               (*  number (recursive_factorial (- number 1)))]))