Missile test to exclude

I am taking the first steps with exception handling in Racket and would like to write a unit test that checks if the procedure throws an exception for a particular input.

The following is what I already have:

The procedure that should throw an exception:

(define (div-interval x y)
  ;; EXERCISE 2.10
  ; exception handling
  (with-handlers
    ([exn:fail:contract:divide-by-zero?
      (lambda (exn)
        (displayln (exn-message exn))
        #f)])

    (if (or
      (>= (upper-bound y) 0)
      (<= (lower-bound y) 0))

      (raise
        (make-exn:fail:contract:divide-by-zero
        "possible division by zero, interval spans zero"
        (current-continuation-marks)))

      (mul-interval
        x
        (make-interval
          (/ 1.0 (upper-bound y))
          (/ 1.0 (lower-bound y)))))))

unit test:

(require rackunit)

(define exercise-test
  (test-suite
    "exercise test suite"

    #:before (lambda () (begin (display "before")(newline)))
    #:after (lambda () (begin (display "after")(newline)))

    (test-case
      "checking interval including zero"
      (check-exn
        exn:fail:contract:divide-by-zero?
        (div-interval
          (make-interval 1.0 2.0)
          (make-interval -3.0 2.0))
        "Exception: interval spans zero, possible division by zero")))

(run-test exercise-test)

There are several more tests in this test suite, but they are for other procedures, so I did not include them in this code. When I run my program, I get the following output:

before
possible division by zero, interval spans zero
after
'(#<test-success> #<test-success> #<test-success> #<test-success> #<test-error>)

Where <test-error>for a test case in this post.

The procedure does not seem to raise an exception.

Is it because I have handlerin my procedure that returns #fand thus already ate the exception?

How do I usually write unit test for raised exceptions?

+4
1

, , with-handler #f. , with-handler , raise, :

(define (div-interval x y)
  (with-handlers
    ([exn:fail:contract:divide-by-zeor?
      (lambda (e)
        <do-stuff>
        (raise e))])
    <function-body>)

, .

, , check-exn - . , check-exn - , thunk, :

(require rackunit)
(check-exn
  exn:fail:contract:divide-by-zero?
  (lambda ()
    (div-interval
      (make-interval 1.0 2.0)
      (make-interval -3.0 2.0))))
+4

Source: https://habr.com/ru/post/1656366/


All Articles