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);
        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:

    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.

1,664 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

  • 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

  • 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

  • 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:-

  • rakesh Says:


    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.


  • 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

  • réparateur informatique nantes Says:

    Très satisfait du service, rendez-vous en jours et explications très
    claires lors de l’intervention à mon domicile je recommande vivement Franck Dépannage!

  • vereeyvn Says:

    そこで、IMEのアイコンがタスクバーから消えた事でWindows8.1に戻しWindows10が落ち着いて、アプリケーションもWindows10に対応するまで8.1の状態で使用する事にした。  リムーバブルメディアのポータブルデスクトップには、インターネットに接続しないで作業できるという利点もある。 [url=http://www.office2016jpjp.net/]produkey windows 10[/url]
    MB2-708認定試験は組織での Microsoft Dynamics CRM のインストールおよび展開を計画している個人を対象としています。 ※5 製品仕様は予告なく変更される場合があります。
    [url=http://softpcjpjp.com/]windows8.1 ストア アプリ[/url] Evernote反乱軍はこの「OneNote Importer」と、どのように闘うのだろうか?また、連合軍であると思われていたGoogleやAppleも、実はこの「クラウド戦争」への準備を着々と水面下で進めていたのであった…。 結局(04/02/2010) Version CLEVOの設定画面なので更新はされて無いようだが、壊れてた設定ファイルか何かが修復されたのかもしれない。
    [url=http://www.officehb.com/]windows 7 の ダウンロード[/url]
    Windows Liveメールはいくつかのメールをまとめて管理できるという意味では便利なのだが、少々重いのと、そもそもそれは今や主流になっているGmail、Outlook.comといういわゆるWebメールと、niftyほかのプロバイダーメールをまとめて管理することに無理があると考えていた。 化粧箱をあけると本体とTypeCの少し大きめの電源ケーブルが入ってました。 [url=http://www.officehb.com/]windows 7 の ダウンロード[/url]
    高品質の70-689トレーニング教材は、あなたがより迅速かつ簡単に試験に合格することを100%保証します。 面倒くさいかもしれませんが、日々のアップデートをお忘れなく。
    [url=http://www.officehb.com/]produkey windows 7[/url] その回答、こちらのネットサイトに寄せれたものがある。 そのバージョンだと4K/60fpsでGPU負荷率は66%強にしか達しないといった情報も出てきているが,本稿では掘り下げない。
    [url=http://windows10kounyuu.blog.jp/]produkey windows 10[/url]

  • Realeouf Says:

    そして翁は、日常を見つめることを怠らなかった。 九日に1人ゴルフで使ったイーグルビジョンのゴルフナビは充電するのを忘れて居たので、今充電して居る所。 [url=http://www.jpgolfoutlet.com/xxio-8-Iron-16915.html]ゼクシオ8ドライバー[/url]
    アディダスのスニーカーですけど実はナイキ派です。 3番アイアンの飛距離だが、やはり安定して狙うには170Y-180Yの距離を狙う時には4番アイアン使う事が出来る。
    [url=http://www.jpgolfoutlet.com/Titleist-714-AP-2-Iron-16926.html]タイトリスト AP2 714 アイアン[/url] レース後に振り返ってみても、気持ちを入れ替えてレースにのぞめたのは良かったなと思います。 カメラマンの持ってるのはソニーのカメラである。
    [url=http://www.jpgolfoutlet.com/Callaway-X-2-HOT-Iron-16939.html]キャロウェイゴルフ X2 HOT[/url]
    沖縄では、1961年に、米軍政下で最高責任者として強権的に振る舞ったと言われるキャラウェイ高等弁務官の名前が、54年がたった今、再び登場した。 いずれ、歴史が、マスメディア関係者を、断罪することとなろう。 [url=http://www.jpgolfoutlet.com/xxio-7-Iron-16911.html]ゼクシオ7 アイアン[/url]
    これについては、次の県知事の言葉が注目される。 対応できる引き出しを増やさんとどにもならんわ。
    [url=http://www.jpgolfoutlet.com/Titleist-716-AP2-irons-16931.html]716 AP2 アイアン 激安[/url] *加工後のフェース割れ等のメーカー、当店での保証は、ありません。 暗殺計画の信憑性はけっして高くは無いと思う。
    [url=http://www.jpgolfoutlet.com/xxio-8-Iron-16915.html]ゼクシオ8 ユーティリティ[/url]

  • RenatoChief Says:

    I have checked your site and i’ve found
    some duplicate content, that’s why you don’t rank high in google,
    but there is a tool that can help you to create 100% unique articles, search for;
    boorfe’s tips unlimited content

  • online jury companies Says:

    dmv Driving Exam…

    Writing The Seemingly Trivial Test | Mindful Mischief…

  • click Says:


    Save time and revenue with top quality bill mail service that’s today in service and makes results today!…

  • Tasia Kosters Says:

    Real nice style and design and great subject matter, nothing else we require : D.

  • essential oils for digestion Says:

    essential oils for digestion…

    Locate now a high quality Essential Oil Side Effects & Warnings currently this week available and now in stock in addition currently available this week only!…

  • oil for acid reflux Says:

    oil for acid reflux…

    Save now a high quality peppermint oil for heartburn currently this week available and in stock in addition at great prices this week only!…

  • metal hands Says:

    metal hands…

    Purchase now swiss clock accessories that’s on available and ready for purchase and cheap for ordering today!…

  • hour hands for clocks Says:

    hour hands for clocks…

    Buy today swiss clock parts for crafts that’s on available and ready to buy and additionally affordable for ordering today!…

  • acid reflux essential oils Says:

    acid reflux essential oils…

    Save now the top The Top 5 Essential Oils For Acid Reflux that are this week available and in stock in addition on sale this week only!…

  • read this post here Says:

    read this post here…

    Hire fast printing and mail services that’s today in service and gets cash flow today!…

  • how to replace clock hands Says:

    how to replace clock hands…

    Buy today swiss clock movements currently on available and ready for purchase and additionally cheap for ordering today!…

  • what essential oil is good for heartburn Says:

    what essential oil is good for heartburn…

    Get now the best oil for acid reflux that’s this week available and in stock in addition currently available this week only!…

  • clock accessories Says:

    clock accessories…

    Purchase now professional clock dials currently on available and ready for purchase and affordable for ordering today!…

  • GeorgettaBig Says:

    Hello. I have checked your davidehringer.com and i
    see you’ve got some duplicate content so probably it is
    the reason that you don’t rank high in google. But you can fix
    this issue fast. There is a tool that rewrites content like human, just search in google:
    miftolo’s tools

  • clock parts manufacturing Says:

    clock parts manufacturing…

    Purchase now high quality clock part currently on available and ready for purchase and additionally cheap for ordering today!…

  • essential oil for gerd Says:

    essential oil for gerd…

    Buy now the top What Is Acid Reflux? that is this week available and now in stock and at the best price this week only!…

  • traffic accident attorney Says:

    traffic accident attorney…

    Get Here a top law offices in omaha nebraska that is here to protect your interests today!…

  • clock Inserts videos Says:

    clock Inserts videos…

    Purchase here high quality Clock kit suppliers currently on available and ready for purchase and cheap for ordering today!…

Leave a Reply