如何为此代码编写测试用例?

问题描述 投票:-1回答:1

我刚刚开始学习树木和堆,我不确定如何编写测试用例。这些代码来自我的课程幻灯片。虽然他们提供代码,但遗憾的是他们没有提供所述代码的测试用例,所以我对如何调用它感到困惑。

我已经尝试过测试用例,例如像5这样的常规整数,我也尝试用列表来处理它,但是我遇到了错误而且它似乎不正确,因为我从图表中知道堆像树一样它的根源是最小的价值和它的子集。

(define (value H)
  (car H))

(define (weight H)
  (cdr H))

(define (create-heap vw-pair left-child right-child)
  (list vw-pair left-child right-child))

(define (h-min heap)
  (car heap))

(define (left heap)
  (cadr heap))

(define (right heap)
  (caddr heap))

(define (insert vw-pair heap)
  (cond ((null? heap) (create-heap vw-pair '() '()))
        ((< (weight vw-pair) (weight (h-min heap)))
         (create-heap vw-pair (right heap) (insert (h-min heap) (left heap))))
        (else
         (create-heap (h-min heap) (right heap) (insert vw-pair (left heap))))))


(define (insert-list-of-pairs vw-pair-list heap)
  (if (null? vw-pair-list)
      heap
      (insert-list-of-pairs (cdr vw-pair-list) (insert (car vw-pair-list) heap))))


(define (remove-min heap)
  (define (combine-heaps h1 h2)
    (cond ((null? h1) h2)
          ((null? h2) h1)
          ((< (cdr (h-min h1)) (cdr (h-min h2)))
           (create-heap (h-min h1) h2 (combine-heaps (left h1) (right h1))))
          (else
           (create-heap (h-min h2)
                        h1
                        (combine-heaps (left h2) (right h2))))))
  (combine-heaps (left heap) (right heap)))
scheme racket r5rs
1个回答
1
投票

您的测试用例应该准确解释您想要做什么。

它们是使用代码解释您编写的函数的预期用途的方法。

对于你的具体情况,我显然无法帮助你,因为这正是你的代码中缺少的东西:它应该具有的含义。

但我仍然可以解释如何在Racket中编写单元测试:

;; This is a function you would write.
;; It does something, but it's not completely obvious
;; how to use it.
(define (find type basket)
  (let ([obj (assq type basket)])
    (and obj
         (cadr obj))))

;; By creating a test module, you add code that describes
;; how to use the functions in this file.
(module+ test
  (require rackunit)

  ;; This is some sample data.
  ;; It's useful to understand what kind of data
  ;; your functions are expected to process.
  (define basket '((bread baguette)
                   (fruit ananas)
                   (fruit banana)
                   (vegetable carrot)
                   (misc fork&knife)))

  ;; Here we call the function and show the expected result.
  ;; It's now clear how to use it.
  (check-equal? (find 'fruit basket) 'ananas)
  (check-equal? (find 'vegetable basket) 'carrot)
  (check-false (find 'fruit '()))
)

您可以使用raco运行这些测试:

> raco test myfile.rkt
raco test: (submod "myfile.rkt" test)
3 tests passed
© www.soinside.com 2019 - 2024. All rights reserved.