Writing The Seemingly Trivial Test

Many people have asked how much time and effort they should spend testing the seemingly “trivial” code that they write. When I first started writing tests, I myself wondered about what types of tests were appropriate to write and how much benefit I would get from testing what seemed to be very trivial code. If the code I am writing is so simple that it can’t possibly be wrong, why should I spend time writing tests for it? What value do those tests provide? A classic example is verifying that preconditions are enforced during object instantiation. It may seem reasonable to test a precondition such as:

    @Test(expected= IllegalArgumentException.class)
    public void theOriginAndDestinationCanNotBeTheSame(){
        Location home = ...;
        new Route(home, home);
    }

This is a precondition for instantiating a new Route as well as being an important requirement for a Route in general.  It seems clear that this is a good requirement to write a test for.   But in my experience, the vast majority of preconditions in a system are more basic and fundamental.   They could include assuring a collection is not empty, or that a String is not empty, or the most prevalent of them all, that an object is not null.

    @Test(expected = IllegalArgumentException.class)
    public void ifYouAttemptToCreateAnEncrytorWithANullKeyAnIllegalArgumentExceptionIsThrown() {
        new BasicStringEncryptor(null);
    }

Should you write tests for all of these seemingly trivial scenarios, especially the null checks? I’ve come to the conclusion that no test is too trivial if it captures an important feature or requirement of the code under test. This is especially true if the code under test is a public API. Here is my reasoning behind this:

  • Catch the typo, the copy and paste error, or the accidentally selected the wrong auto code completion option: This is probably the least important reason but I’ve definitely seen these problems more than a few times in what you would think is trivial code.
  • Writing the test forces you to think about how the consumer of the code will try to comprehend and attempt to us the code.
  • What you think is simple and obvious isn’t always so: What you view as obvious while writing the code may not be so obvious to the many people who will read your code as they attempt to enhance or maintain it.
  • The tests provide a live, runnable specification: The specification can document the expected usage of the code as well as what you can and can’t do with the code. For example:
  •     @Test(expected = IllegalArgumentException.class)
        public void ifYouAttemptToCreateAnEncyprotWithANullKeyAnIllegalArgumentExceptionIsThrown() {
            new BasicStringEncryptor(null);
        }
     
        @Test
        public void anEncryptorCanBeCreatedWithAValidKeyAndANullProviderClass() {
            assertThat(new BasicStringEncryptor(new Key(), null), is(notNullValue()));
        }
  • The tests provide a hint to the future developer that they need to think twice about changing this behavior: Countless times I have wondered whether or not I could safely change seemly trivial bits of code not knowing whether or not the behavior was assumed to be part of the specification or if the original developer had even considered it.
  • If it is a public API, people may be depending on that behavior: This goes hand and hand with the pervious point.

The examples to this point have been weighted towards simple preconditions, which I think is only one type of seemingly trivial test. Another scenario is a test whose implementation is very similar to the implementation of the code under test. Consider the following test:

    @Test
    public void theLocationIsTheIPAddressOfTheNodeWhereTheCodeIsRunning()
            throws UnknownHostException {
        InetAddress localhost = InetAddress.getLocalHost();
        Event event = ...
        assertThat(event.getLocation(), is(equalTo(localhost.getHostAddress())));
    }

The implementation behind getLocation() is probably pretty similar to the code in the test. So why would you want to write virtually the same code in the test?

  • Again, the test provides a live specification
  • It allows you to make sure your code really does work at a micro-level before you incorporate it into a higher level acceptance test
  • The code may be refactored as some point: In the example above, you may have realized that your original implementation wasn’t performing as well as it needs to because each call to InetAddress.getLocatHost() required a DNS lookup. So you decide to cache the lookup or use a static field to store the result. The implementation is suddenly less trivial and the test case exists to verify your changes.

I recently heard an interview with “Uncle Bob” Martin where he compared a developers use of TDD and writing tests to an accountant’s use of double-entry bookkeeping. Double-entry bookkeeping is a pretty good metaphor for the types of tests I describe here (and for tests in general, which is basically Uncle Bob’s point).

So what about the time involved in writing these tests. I don’t buy the argument that writing these types of tests takes too much time. Many of these test will take you no more than 30 seconds to write, are very easy to read, and run very quickly. So give it a try and let me know what you think.


179 Responses to “Writing The Seemingly Trivial Test”

  • toko baju wanita online Says:

    Hey there, I think your site might be having browser compatibility issues.
    When I look at your blog site in Ie, it looks fine but when browsing in Explorer, it has
    some overlapping. I just wanted to give you a quick heads
    up! Other then that, fantastic blog!

  • Cerrajerossantcugat24h.pw Says:

    The World Wide Web is an important marketing medium and to
    gain success in this arena a marketer should have well planned online marketing strategy.
    As with any online marketing activity, keep the message short, sweet and direct and be sure
    to include the necessary contact information needed to send in a referral.

    Both reach and targeting are very important factors to
    be considered when drafting digital marketing plans as they significantly affect the effectiveness of the plan.

  • english teaching Says:

    No matter if some one searches for his required thing, thus he/she desires
    to be availazble that in detail, therefore that thing
    is maintained over here.

  • Leilani Says:

    Hey I am so happy I found your webpage, I really found you by
    error, while I was searching on Bing for something else,
    Anyways I am here now and would just like to say thanks a lot for a incredible post and a all round thrilling
    blog (I also love the theme/design), I don’t have time to read through it all
    at the minute but I have saved it and also added your RSS feeds, so when I have time I will be back to read much more, Please do keep up the excellent b.

  • 5196 Park County Road 14 Fairplay Co Says:

    Noticed this amazing propperty and figured you need to consider
    it!

  • weight loss for women Says:

    I do believe all the ideas you have introduced to your
    post. They are very convincing and can definitely work.
    Nonetheless, the posts are too brief for beginners. May you please extend
    them a bit from next time? Thank you for the post.

  • diablo 3 gold Says:

    hi there, Hey you should assist me to alter the elgg, sociable torch motif to at least one. 6 You should i want to learn which usually page with mod to help alter to produce my very own structure with the active operation Oughout must make your personal ‘layouts’. Ex., straight into binder ‘views

  • limousines montreal Says:

    The story likmousine service montreal is automatcally simplified.
    Here, airport transfer, wedding parties to proms and othgerwise unscheduled events.

    People who wish tto stay ofer night, the it’s advisable
    that you get value for your shuttle arrives.

    My weblog limousines montreal

  • live gold prices Says:

    Shortly after the historical excessive gold worth, it entered into free fall
    and fell as little as the $300 mark.

  • iPhone 6 review Says:

    You can use it with talking over the web has evolved just as iphone 6 reviewsturdy.
    So guys I hope that their beloved ggadget is available
    in the market.

  • remboursement dentaire Says:

    Still, thre have been a numbr of x-rays and trips to the ‘basic services’
    like sute web tooth removal. You can take you take a look at dental care is an extremely arfordable price.
    How do site web they carry any deductibles or yearly fee, and reasonable.
    While full coverage dental insurance can be cumbersome and costly dental premiumss
    thann others?

    My blo post remboursement dentaire

  • vacation Says:

    Hi it’s me, I am also visiting this website on a regular basis, this ste
    is genuinely good and the visitorrs are in fact sharing
    good thoughts.

    Here iis my web page – vacation

  • zach lavine vertical Says:

    He played for the Warriors, Sixers and the Lakers, and retired with a total of
    31,419 points, averaging 30. Without finding it, you can pletely spoil the situation. If you are in the business of selling NBA snapback hats, then its time for you to consider getting wholesale cheap NBA snapback hats.

  • http://orderfitnesspoints.co.uk Says:

    I think the admin of this site is actually working
    hard in favor of his site, because here every material is quality based information.

    For an incredible review please jump over to this page; orderfitnesspoints.co.uk
    (http://orderfitnesspoints.co.uk)

  • testoriladvice.com Says:

    A motivating discussion is definitely worth comment.
    I do believe that you need to publish more about this
    issue, it might not be a taboo subject but
    generally people don’t discuss these topics. To the next!
    Kind regards!!

    For a better answer please check-out this amazing site – brainfire reviews (testoriladvice.com)

  • vidente buena Says:

    Article writing is also a excitement, if you
    be acquainted with afterward you can write otherwisde it
    is difficult to write.

  • Vestido de Mulher Says:

    We mention also a big offer in matter of products: dresses, lingerie, bags for
    women, sandals and everything it’s necessary for a woman dress.
    and pale blues, greens and reds would have been common. With extensive measures taken up, plus size blouses have been designed in solid colors which
    never happened earlier.

    My site Vestido de Mulher

  • semnas.fmipa.unpad.ac.id Says:

    %first_paragraphThe three locations have slightly different hours of operation but they all have the same quality and service you have come to expect in the last sixty years. The best news concerning this is there are three of these visions centers set up for your convenience, the Optometrist St Arnaud offices, the Optometrist Stawell offices, and the Optometrist Ararat offices. For the last three generations the Blizzard Optometrist offices have been providing great customer service and quality eyewear to the people of Australia. So naturally when someone in this country thinks of eye examinations and buying glasses they think of this vision care center first.

    There are many reasons people like to go to an optometrists for their vision problems. They can provide a wide variety of solutions for their patients. They are also equipped to deal with these problems in the best possible manner. Optometrists are not so much into eye care as they are into vision care. Therefore, they use state of the art detection systems and eye exams to diagnose the minutest of problems.

    They are there to examine and diagnose your eyes, as well as give sufficient treatment to correct poor eyesight. This treatment isn’t a bottle of “good-eye” pills, or a needle full of eyesight, it is vision correction throught the use of lenses and other optical aids. Glasses and/or contact lenses are the norm for perscriptions by doctors in the field of optometry. I’m not trusting them to some ‘doctor’ who can harass me with medical jargon” Luckily, I have your solution. Now I know there are a few readers out there who are thinking “These eyes are mine!

    There are even trained eye specialists providing glasses in malls nowadays. But optometrists do a lot more than that. A lot of people think of these people only as the ones who perform a yearly eye test and prescribe glasses if needed.

  • Easy Spy Cell Tracker Says:

    Fantastic site. Lots of helpful info here. I am sending it to some pals ans
    additionally sharing in delicious. And certainly, thank you to your sweat!

  • pesadilla Says:

    I go to see day-to-day some blogs and websites to read posts,
    except this web site offers quality based content.

  • http://www.mountainblog.it Says:

    Although being aware of keyword percentages is a good idea, it is more important that
    content be relevant and useful to the visitor.
    The process of SEO is the series of steps that are undertaken to ensure that a website
    is visible among internet users to an optimal level.
    But it is extremely important that anyone looking to hire an SEO professional be
    aware of the differences. A reputable SEO company
    won’t have any qualms about connecting potential clients
    with former ones.

    My blog http://www.mountainblog.it

  • skull mp3 downloads Says:

    Hey there I am so delighted I found your webpage, I
    really found you by mistake, while I was
    searching on Digg for something else, Nonetheless I am here now and would just like to
    say thank you for a fantastic post and a all round interesting
    blog (I also love the theme/design), I don’t have time to
    look over it all at the minute but I have book-marked it and also added your RSS feeds, so when I have time I will be back to read
    a lot more, Please do keep up the great
    jo.

  • Lavender oil - Wikipedia, the free encyclopedia Says:

    I am uncertain I know of anything that will last even as long as
    the earth remains, with possibly the exceptions of diamonds
    and human being ignorance LOL.

  • http://del.icio.us/bagensdyuw Says:

    He mohamed writing to my father: “dear dad, I’m sorry to write to you, I need one hundred francs. I don’t want to lend money to you, but how also get to you, because it has

  • Ruben Says:

    Hello, all is going nicely here and ofcourse every one is
    sharing data, that’s genuinely fine, keep up writing.

  • Rkvit solutions pvt ltd Says:

    Leading software and website development company in Patna:-

    Rkvit solutions pvt ltd is a leading software company in patna. we, bring successful years in it world along with the team of highly professional expertise. our service includes website development in Patna, website design in patna, web design in patna,
    seo company in patna.

    For more information:-
    http://www.rkvitsolutions.com/

  • rakesh Says:

    AFFORDABLE AND ATTARCTIVE WEBSITE AND SOFTWARE DEVELOPMENT COMPANY:-

    rkvit Solutions pvt. Ltd. is a main programming organization in Patna. We, get effective 4 years IT world alongside the group of profoundly expert skill.Our administration incorporates site improvement in Patna, site outline in Patna, web plan in Patna, SEO organization in Patna.

    http://www.rkvitsolutions.com/

  • weight loss shakes Says:

    I’m afew pounds off my ideal goal weight, though my brain occasionally has problems
    catching-up with my body measurement.

  • flipboard.com Says:

    Unquestionably believe that which you said.
    Your favorite reason appeared to be on the internet the easiest thing to
    be aware of. I say to you, I certainly get annoyed while people think about worries
    that they just don’t know about. You managed to hit the nail upon the top and
    defined out the whole thing without having side-effects , people can take a signal.
    Will probably be back to get more. Thanks

    Feel free to surf to my web site; credit monitoring services
    (flipboard.com)

Leave a Reply