Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I expect failure in a unit test?

We're writing unit tests for our code in Clojure using clojure.test.

Some of our tests ignore the API and purposely break the code, in order to serve as documentation for latent deficiencies in the code.

However, we want to distinguish between failures of these tests, and failures of normal tests.

We haven't seen any suggestions in the clojure.test documentation -- only (is (thrown? ...)), which of course doesn't do what we need.

Any suggestions? Basically, we're looking for something like (is (not <condition>)), except that the test framework should record an expected failure -- something like this.

like image 885
Matt Fenwick Avatar asked Oct 21 '11 15:10

Matt Fenwick


People also ask

How do you fail building if unit tests fail?

Add set -e as the first line of your build hook yaml , locate your build hook and add set -e as the first line. If one does not exist go ahead and create it. That tells the system to fail the build if any command in the build hook returns an error code.

What does the fail method do in a unit?

fail() method It can be used to verify that an actual exception is thrown. Usually based on some input when test case expects an exception at a certain line, providing fail() below that line will verify that exception was not thrown as code execution reached fail() method line. Thus, it explicitly fails the test case.

What are possible outcomes for unit test test?

Three possible outcomes exist for each test method: success, failure, or error.

How do you fail test cases?

In case of Test3, the tester is purposely trying to cause the test case to fail in order to showcase how to run failed test cases. Therefore, the code includes @Asert. assertTrue(false); to fail this particular test case.


2 Answers

I have made tests throw an exception when they 'fail' like this, and then used thrown? to test if the exception arrives as expected. There very well may exist a more elegant way, but this gets the job done.

like image 78
Arthur Ulfeldt Avatar answered Oct 15 '22 09:10

Arthur Ulfeldt


As @andy said you can rebind report function.

(defmacro should-fail [body]
  `(let [report-type# (atom nil)]
     (binding [clojure.test/report #(reset! report-type# (:type %))]
       ~body)
     (testing "should fail"
       (is (= @report-type# :fail )))))

And use this macro like this:

(should-fail (is (= 1 2)))

That will be successful passing test.

like image 29
hsestupin Avatar answered Oct 15 '22 08:10

hsestupin