对于相同的预期值和实际值,Clojure 测试失败

Clojure tests fails for identical expected and actual values

我正在做一个基本上模拟汽车 assemble 工厂的 Clojure 练习。以下代码是我的“生产”代码。

(ns cars-assemble)

(def success-rate-frequencies [
  { :id 1 :interval #(= % 0), :rate 0 }
  { :id 2 :interval #(and (> % 0) (<= % 4)), :rate (/ 100 100) }
  { :id 3 :interval #(and (>= % 5) (<= % 8)), :rate (/ 90 100) }
  { :id 4 :interval #(= % 9), :rate (/ 80 100) }
  { :id 5 :interval #(>= % 10), :rate (/ 77 100) }
])

(defn get-rate-by-speed-interval [speed]
  (let [result (first (filter #((get % :interval) speed) success-rate-frequencies))]
    (get result :rate)))

(defn production-rate
  "Returns the assembly line's production rate per hour,
   taking into account its success rate"
  [speed]
  (float (* speed (* 221 (get-rate-by-speed-interval speed)))))

(defn working-items
  "Calculates how many working cars are produced per minute"
  [speed]
  (let [production-rate (production-rate speed)]
    (if (= speed 0) 0 (int (/ production-rate 60)))))

我的问题是,出于某种原因,当我 运行 测试时,生产代码 returns 的值是正确的,但测试仍然失败。下面是我的测试示例。

(deftest production-rate-speed-10-test
(testing "Production rate for speed 10"
  (is (= 1701.7 (cars-assemble/production-rate 10)))))

这是我的命令的输出 lean test:

FAIL in (production-rate-speed-10-test) (cars_assemble_test.clj:27)
Production rate for speed 10
expected: (= 1701.7 (cars-assemble/production-rate 10))
  actual: (not (= 1701.7 1701.7))

我试图检查它是否有任何类型的隐藏字符,但没有找到任何东西。

我尝试过的另一件事是手动修改测试文件,将预期值转换为 float(如下例所示)。但我不应该更改我的测试文件。

(is (= (float 1701.7) (cars-assemble/production-rate 10)))

= 函数检查参数是否具有相同类型的浮点值,因此当您实例化一个十进制数时,如:

(def my-decimal-number 12.000)

你实际上是在实例化一个java.lang.Double。当您将其与 production-rate 函数的 returned 值进行比较时,您将收到错误消息,因为类型不同。只是为了将函数 production-rate 更新为 return 而不是 double

(defn production-rate
  "Returns the assembly line's production rate per hour,
   taking into account its success rate"
  [speed]
  (double (* speed (* 221 (get-rate-by-speed-interval speed)))))