简体   繁体   中英

A way to chain the test, one running after the other in clojure?

Lein test runs my functions in random order.

I have two functions that modify the same data. I need the first one running first and the second one after that. The order in my test firles

Example:

;;===============my file=============
;;this fails if x and y are not found.
(defn create-data [x y]
  (go add x y))

;;if the update function doesn't find x and y it adds them so create-data fails when it runs after update-data
(defn update-data [x y]
  (go update x y))

;;======my file test=======
(deftest create-test
  (testing "this should run first"
   (is (= 20 create-data)))

(deftest create-test
  (testing "this should run second"
   (is (= 20 update-data)))

so I thought creating one test for both functions will make it work but it doesn't.

(deftest test-create-update.
  (testing "this should run second"
    (is (= 20 create-data))
    (is (= 20 update-data)))

I want something that will run both functions but will run create-data first for sure and regardless of the result (whether passed or failed) will run the update-data. I need both in my test. Individually they work. but i need automated testing.

You could use test fixtures to create and tear down test environments. This can be done for all tests, or on every individual tests.

See use-fixtures :

; Here we register my-test-fixture to be called once, wrapping ALL tests 
; in the namespace
(use-fixtures :once my-test-fixture)

If you want to enforce order over several namespaces, you could wrap them in my-test-fixture .

Your intuition for creating one test for both functions is a fine approach. The issue you are having is most likely not related to testing.

The code you posted (go add xy) suggest you are using core.async. There are some problems:

  1. go blocks return a channel and the code in them is executed "sometime later", so unless you block on the result, you are not guaranteed that anything has happened.
  2. (go add xy) does not perform any functions, it just returns y. You probably want (!< (go (add xy)))
  3. Unless add modifies some state via an atom or ref or similar, nothing will have changed.

I believe the real problem here is with the code, not the tests. Or if the code "works" then it is because you have no blocking in your test. Can you please provide more detail on what go and add are in your context?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM