Wednesday, November 19, 2008

Testing private methods, TDD and Test-Driven Refactoring

While being a TDD--Test Driven Development--coach, I am always asked about testing private methods. I finally decided to write about my experience on testing private methods.

When really doing TDD (i.e. writing the test code before writing the functional code, and then refactoring the code) private methods are guaranteed to be test covered. When driving the functional code design and implementation from the unit test (aka Test Driven Development), no method is created private. Instead, the private methods are extracted—extract method refactoring step--from a public or package level method. The Example 1 below presents a scenario on applying TDD and how the private method is created.

New code development following TDD

Example 1: new code development following TDD

Consider the development example following a TDD sequence for creating methodA and methodB.

  1. create testMethodA/ create methodA/ refactoring
  2. create testMethodB/ create methodB/ refactoring: extract methodC

On the first sequence, the testMethodA is created for validating the functionality expected of methodA. The methodA is successfully created: All tests including the testMethodA are passing. Then you look for improvements in the code; refactoring.

On the second sequence, the testMethodB is created for validating the functionality expected of methodB. The methodB is successfully created. All tests including the testMethodB are passing. Then you look for improvements in the code; refactoring.

While looking for improvements in the TDD Refactoring step, you recognize that methodA and methodB have a common fragment of code (code duplication). You extract the common code fragment into a private method whose name explains the purpose of the method--methodC. Then methodA and methodB invoke methodC.

In this example testMethodA covers methodA, which invokes private methodC; therefore the private methodC is test covered.

Please keep in mind that this is a simplified example. Your methods and tests should not read like testMethodA / methodA, and testMethodB / methodB. Jeff Patton describes how test cases can describe design in his Test-Driven Development Isn’t Testing paper.

When doing TDD, the private methods emerge from your code. And because you test-drive your development, no functionality is added without a test. So, for code fully developed by following TDD you won’t have to test the private method separately: Private methods are already being tested by previously written tests.

Improving legacy code following Test-Driven Refactoring

Now let’s look into a more realistic example. The majority of the code I have been working on is not new code; therefore I am not doing pure TDD; instead, I am doing Test Driven Refactoring,

Test-Driven Refactoring

Test-Driven Refactoring is an evolutionary approach to improve legacy code which instructs you to have test-proven refactoring intent. Basically, you start by writing a passing test around the code to be improved, and then you refactor the code; improving its internals, yet still passing the test suite.

While doing Test Driven Refactoring, I am trying to perform small refactoring steps and, at times, I find myself attempting to test a private method. This typically happens when I am working on an existing code base with very low test coverage. And the public methods are too complex to write tests for.

Example 2: test driven refactoring for existing low test coverage codebase.

Consider that you want to improve the following code:

public void overstuffedMethodX(){


// very complex code

// invoke private method methodY()
someString = methodY();

}

private String methodY (){

}

In the scenario presented in Example 2, the public method does not have corresponding unit tests. And I don’t feel comfortable refactoring code which does not have tests around it. Therefore I will follow Test-Driven Refactoring for improving the code. Below I will explain two different approaches for doing Test-Driven Refactoring for improving the code in Example 2.

Top down Test-Driven Refactoring

First you create tests for the complex public method:

public void testOverstuffedMethodX(){…}

At this point there is test coverage around the overstuffedMethodX() functionality, so you are able to refactor the overstuffedMethodX() code, including refactoring for the private method methodY().

In the top down Test-Driven Refactoring approach, first the unit test for the public method is created, and then its internals (including the private methods) are refactored.

Let’s now look into another approach.

Bottom up Test-Driven Refactoring.

No test for the complex public method is created.

Instead you look for smaller pieces of improvement.

You change the access level for the private method to make it accessible from a unit test.

private String methodY (){}

becomes

String methodY (){} // package level access in Java

Then you write test for methodY()

public void testMethodY (){…}

Then you refactor methodY(), and verify that the improvement works as the testMethodY() test still passes.

In the bottom up Test-Driven Refactoring approach, you first improve the test coverage and the code for the private methods and the internals of the complex overloaded method. By doing so, the code becomes less complex; after that you can start moving up the chain, increasing and broaden the test coverage until you are able to take care of the public method.

When applying the bottom up Test-Driven Refactoring approach for Example 2, the private methodY() is made package level in order to be accessible by its corresponding unit test (consider the package access level for the Java language). Similarly to testMethodY(), other tests are added in a bottom up approach. After increasing the test coverage and improving the code internals, it becomes easier to create testOverstuffedMethodX(), and finally, refactor the overstuffed complex method.

Top down versus Bottom up Test-Driven Refactoring

Even I consider the top down approach to be more purist as it does not change the private methods access level, its implementation is not always straightforward. The public method might be almost “untestable” (e.g., static, dependencies, long, complex) in its current state. For such cases, a bottom-up approach might be more suitable. As I see it today, code refactoring activity is a combination of bottom-up and top-down approaches that enables you to have small proven steps towards a cleaner solution, which still keep the same interface (the external behavior which is verified by the test suite).

Bottom-line, while doing Test Driven Refactoring, I have provisionally added tests for the private methods. In Java, I deliberately remove the private namespace from the method declaration, changing the method access level to package access level. This way, the corresponding test class--located under the same package--can invoke the method and test it.

But I won’t stop the refactoring until I remove the test for the private methods. I have experienced two refactoring sequences which finish without explicit tests for private method.

In the first refactoring sequence, some later refactoring step moves the private method to a different class. Basically, you realize that the method’s functionality is beyond the original class’s purpose; you identify, create the new class, and move the method – which now is public access level.

In the second refactoring sequence, the method access level goes back to being private and you delete the test which was directly invoking it. Because of the increasing test coverage--as a result of the Test Driven Refactoring--new test scenarios are added for the public method which invokes the private method. Once you (perhaps assisted by test coverage and analysis tools) realize the extra test coverage on your private method, you perform my preferred refactoring step--unnecessary code deletion. The test for the private method can be safely deleted as its functionality is being tested by another test method.

Should I add test for private methods?

So, here is my answer to the test private method question: After successfully doing TDD or Test-Driven Refactoring, your code will not have specific tests for the private methods.

If you are developing new code, you are following TDD. You test-drive the development and no functionality is added without a test. Private methods are only created as the result of a refactoring step. And the path of code going through the private method is already being tested by previously written tests. So, after successfully doing TDD, your code will not have specific tests for the private methods.

If you are improving a legacy code, you should be following Test-Driven Refactoring. In this case, you may provisionally add tests for private methods. Gradually, with the increasing test coverage, the tests for the public methods will cover all the paths, including the paths going through the private methods. At this point, you don’t require the tests for private methods anymore. So, after successfully following Test-Driven Refactoring, your code will not have specific tests for the private methods.

75 comments:

  1. Hi, One thing I was using in my test when I really really wanted private access for method was through reflection. You can easily create a method inside your test which is reflectively calling the private method. This of course has shortcomings (no compile time verification, not really seen in test what you're calling) but still sometimes it is a viable approach.

    ReplyDelete
  2. Thats the cool’s themes i have see in a long time.
    Very nice

    ReplyDelete
  3. description Wailua-DL140

    ReplyDelete
  4. This glasses article is definitely eye-opening and inspiring.

    I greatly benefit from your articles every time I read one. Thanks for the eyewear info, it helps a lot.

    Excellent point here. I wish there are more and more eyeglasses online articles like that.

    I like your ideas about cheap eyeglasses and I hope in the future there can be more bright articles like this from you.

    I really like this prescription glasses article, and hope there can be more great resources like this.

    I am glad to read some fantastic cheap kids glasses article like this.

    You have given us some interesting points on child eyeglasses. This is a wonderful article and surely worth reading.

    Good job for writing this brilliant article of children eyeglasses.

    Your do have some unique ideas here and I expect more kids sunglasses articles from you.

    I appreciate your bright ideas in this unisex glasses article. Great work!

    Thank you so much for sharing some great ideas of metal eyeglasses with us, they are helpful.

    We share the opinion on plastic eyewear and I really enjoy reading your article.

    Great article, it's helpful to me, and I also like the useful info about titanium eyewear.

    It has been long before I can find some useful articles about aviator eyeglasses. Your views truly open my mind.

    I love this rimless glasses article since it is one of those which truly convey useful ideas.

    ReplyDelete
  5. I appreciate your bright ideas in this nds card article. Great work!

    Thank you so much for sharing some great ideas of nintendo ds with us, they are helpful.

    We share the opinion on ez flash vi and I really enjoy reading your article.

    Good job for writing this brilliant article of dstti card.

    Excellent point here. I wish there are more and more dstt card articles like that.

    I am glad to read some fantastic m3 dsi article like this.

    What an inspiring article you wrote! I totally like the useful r4 info shared in the article.

    Your do have some unique ideas here and I expect more r4 dsi articles from you.

    I love this r4 sdhc article since it is one of those which truly convey useful ideas.

    Great article, it's helpful to me, and I also like the useful info about ak2i cards.

    I greatly benefit from your articles every time I read one. Thanks for the acekard 2i info, it helps a lot.

    It has been long before I can find some useful articles about nintendo ds card. Your views truly open my mind.

    I really like this M3 Adapter article, and hope there can be more great resources like this.

    ReplyDelete
  6. Young and creative style
    abercrombie and fitch
    You can have a look at it.
    abercrombie & fitch
    if you really want it
    jordan 8
    jordan 9
    jordan 10

    ReplyDelete
  7. many fendi products for discount
    go to buy fendi handbags on sale
    fendi spy bag fendi handbags
    get your gucci set at cheap price
    gucci gucci replica all so very good
    choose gucci handbags high quality
    new arrive miu miu handbags miu miu bags
    beauful miu miu bags on sale
    large numbers of miu miu sale
    chanel designed the famous suit
    authentic chanel handbags on this
    looking for cheap chanel bags chanel
    gucci bags luxury bags louis vuitton bag
    -----------
    as a luxury consumable luxury handbags sale
    good quality lv bags online store
    louis vuitton bags remains one of the world
    carried on the louis vuitton luggage the body
    looking for cheap louis vuitton handbags handbags
    all kind of louis vuitton bags for sale
    you need louis vuitton wallet to put money
    luxury louis vuitton bags for sale
    luxury louis vuitton louis vuitton bags
    have large numbers of louis vuitton shoes discount
    louis vuitton bag louis vuitton handbag for discount
    discount louis vuitton louis vuitton discount
    have louis vuitton shoes is symbol of fashion
    this louis vuitton shop sale louis vuitton
    have a stylish lv handbags is every women dream
    a pair of louis vuitton shoes becoming fashion

    ReplyDelete
  8. Among so many affordable luxury bags, some people just follow suits, but for the wise fashionista, they know how to use the same money.


    Louis Vuitton Handbags Mall captures fans of discount handbag and discount purse with stylish style and high-quality materials.

    miu miu handbags are famous in Europe, however, not all of Miu Miu fashion fans know the origin of evolution of Miu Miu.

    When Louis Vuitton and Hermes witness sales growth, China will certainly witness an increasing number of wholesale designer handbags.


    The latest series Gucci replica designer handbags abide by the leading Italian luxury quality and reveal the understanding of fashion.

    What attracts the professionals is "The Blueberry Nights" is the fruit of cooperation between luis vitton and the film industry.

    The general term is one to three days and designer handbags rent is together with a commission fee but you must pay the full deposit.

    ReplyDelete
  9. This comment has been removed by the author.

    ReplyDelete
  10. This comment has been removed by a blog administrator.

    ReplyDelete
  11. Good.It has been long before I can find some useful articles about Laptop Batteries. Your views truly open my mind. I really like this Replacement Laptop Battery article, and hope there can be more great resources like this. What an inspiring article you wrote! I totally like laptop battery
    laptop batteries
    acer laptop battery
    laptop battery UK
    laptop keyboard
    dreambox 500c
    laptop akkus
    shopping
    dreambox 800s

    ReplyDelete
  12. Thank you for the guiding, leaning form you, thanks.
    welcome to our pc parts store.
    pcpartsltd.com

    ReplyDelete
  13. The EVA outsoles current provides a great offer of traction and cushioning and stay obvious of any probabilities of strain inside the feet.Moncler Online one can stays apart from a great offer of discomfort even although placing on this sort of beautiful UGG boots.Ugg Boots Outlet UGG boots from Mezoboots.Ugg Outlet Store com are quite lightweight and so are designed of EVA/rubber.Uggs boots uk These UGG boots are built to ensure which they could possibly be used devoid of socks only. Our boots that take place to be designed of pure sheepskin are this sort of which they adjust by themselves according for the dimension by stretching the leather.Ugg Clearance Sale I do not experienced very much make any difference picking among several possibilities current inside the website.ugg outlet It's effortless to decide on the size, the colours as well as the design and design that you simply need within your UGG boots within your website.Ugg Boots Clearance Sale I acquired my pair of UGG boots within of 5 times of placing my purchase inside the internet website - mazoboots.com. The UGG boots that take place to be supplied inside the internet website are also not prized the sky.uggs clearance Most using the traditional assortment is supplied for much lower than hundred dollars.uggs clearance That is typically a wonderful bargain and I am preparing to purchase one more one. subsequent all, these quite brightness unwanted fat UGG boots can perform wonders to feet. blog.ugg boots usa. Ugg UK. Ugg Boots Outlet. ugg australia uk. Ugg Boots UK. Ugg Online Store

    ReplyDelete
  14. Agree with the above saying.
    http://www.salelvbagsonline.com/
    http://www.luxurylvbagsus.com/
    http://www.picklvbags.com/

    ReplyDelete
  15. Thanks for sharing. I hope it will be helpful for too many people that are searching for this topic.
    Signature:
    Jugar juegos de frozen en línea gratis, los nuevos de princesa de Disney juegos frozen - la princesa encantadora y linda. Divertirse frozen!

    ReplyDelete
  16. This is just the information I am finding everywhere. Thanks for your blog, I just subscribe your blog. This is a nice blog. Lehenga sarees

    ReplyDelete
  17. This post is among the pages that i have found to be very interesting, and maybe if it were not for the search engines i wouldn't have found it. The tips you are offering are very helpful and informative. Keep up with the good work.
    Flamingo Statue

    ReplyDelete
  18. Quite and interesting post, much like zayn let me mp3 download which I came across while browsing for free Fakaza mp3 download on hip hop mp3 download.

    ReplyDelete
  19. I like the side of the article, and very like your blog, to write well and hope to continue their efforts, we can see more of your articles. After reading this article has strong feelings, the future will be Hindigana

    ReplyDelete
  20. The trunk has a higher exposure to heat and humidity that’s why it is not advisable to place it there. South African Mp3 Download

    ReplyDelete
  21. Ex-housemate, Tega has boldly justified her actions by saying that even if she slept with Boma Akpore in the house, the show is rated 18+, which invariably means that such a thing shouldn’t come as a surprise to people.

    The married housemate and Boma upon exiting the house were under fire over their sexcapades in the house. This led to a lot of explanations from the duo as they maintained that nothing really happened rather it was just staged/scripted for the purpose of entertaining the viewers.

    However, after all said, the mother of one has surfaced to lash out heavily at critics while stating that the show rated 18+. She also asserted that all these are in the past now and they have moved on.

    Watch the video below:



    South Africa

    ReplyDelete
  22. I really appreciate the kind of topics you post here. Thanks for sharing us a great information that is actually helpful. Black Label Society Denim Vest

    ReplyDelete
  23. Our the purpose is to share the reviews about the latest Jackets,Coats and Vests also share the related Movies,Gaming, Casual,Faux Leather and Leather materials available Ghost Modern Warfare Jacket

    ReplyDelete
  24. I love to recommend you Where can crawl Exciting Products latest Jackets, Coats and Vests Click Here Chris Redfield Vest

    ReplyDelete
  25. Nice Blog !
    Here We are Specialist in Manufacturing of Movies, Gaming, Casual, Faux Leather Jackets, Coats And Vests See. Chris Pine All the Old Knives Peacoat

    ReplyDelete
  26. sand coin nedir? sand coin geleceği. sand coin hakkında bilgiler. sand coin fiyatı.

sand coin nedir

    ReplyDelete
  27. Propysalford akıllı şehir mobilyaları ya da akıllı kent mobilyaları. akıllı şehir mobilyaları için web sitemizi ziyaret edebilirsiniz.

    ReplyDelete
  28. Your writing consistently helps bridge the gap between knowledge and action. This post offered detailed insights along with practical steps that I’m eager to try out for myself.

    USA Jacket Store

    ReplyDelete