Jay Fields is a software developer at DRW Trading. He has a passion for discovering and maturing innovative solutions. His most recent work has been in the Domain Specific Language space where he's delivered applications that empowered subject matter experts to write the business rules of the applications. He is also very interested in maturing software design through software testing. Jay is a DZone MVB and is not an employee of DZone and has posted 116 posts at DZone. You can read more from them at their website. View Full User Profile

Clojure: Expectations, Customize your Test Running Context

04.18.2013
| 3043 views |
  • submit to reddit
I've previously written about expectations' before run hook and the built in support for detecting state changes. These features are nice for reassigning vars you don't care about or detecting accidental state changes; however, there was no option for temporarily changing the context in which your tests are run. As of expectations 1.4.36, that's no longer true.

Version 1.4.36 allows you to alter the context in which your tests run by creating a function that takes the "run the tests" function as an arg, and do you as wish.

Too abstract, no problem, the code:
(defn in-context
"rebind a var to verify that the expecations are run in the defined context"
{:expectations-options :in-context}
[work]
(with-redefs [success.success-examples-src/a-fn-to-be-rebound (constantly :a-rebound-val)]
(work)))
That's it, if you add the previous function to your tests, you can define whatever you like in the in-context function, and your tests will be run in your custom context. The previous snippet is pulled from the expectations tests, which verify that success.success-examples-src/a-fn-to-be-rebound is correctly rebound. In the expectations tests an expectations_options.clj namespace is used to define in-context (expectations_options.clj explained here).

Why would you want to define your own context? In the past I've used in-context for two reasons: rebinding things I don't care about (e.g. calls to logging) to (constantly true), and rebinding things I never want called (e.g. create a new thread) to #(throw (RuntimeException. "not allowed in tests"))

I've been using in-context for about a month now, and it's worked well for me. Give it a shot and let me know how it's working for you.

 

Published at DZone with permission of Jay Fields, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)