Sunday, February 6, 2011

Parametrized Junit Tests: Postscript

In two earlier blog posts I commented on parametrized junit tests. This blog post will complement these post with an example of a piece of code.

Because all the important points are made in the other posts I will only present the Junit runner I created. A Maven project demonstrating this technique can be found code at my minimal examples repository

Without further ado: the Junit runner.

package org.junit.runners;

import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.junit.runner.Runner;
import org.junit.runner.notification.RunNotifier;
import org.junit.runners.Parameterized.Parameters;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.InitializationError;
import org.junit.runners.model.Statement;
import org.junit.runners.model.TestClass;

public class ParameterizedWithBuilder extends Suite
{
        private class TestClassRunnerForParametersWithBuilder extends BlockJUnit4ClassRunner
        {
                private final int fParameterSetNumber;

                private final List<Object> fParameterList;

                TestClassRunnerForParametersWithBuilder(Class<?> type, List<Object> parametersList, int i)
                        throws InitializationError
                {
                        super(type);
                        fParameterList = parametersList;
                        fParameterSetNumber = i;
                }

                @Override
                public Object createTest() throws Exception
                {
                        return getTestClass().getOnlyConstructor().newInstance(computeParams());
                }

                private Object computeParams() throws Exception
                {
                        try
                        {
                                return fParameterList.get(fParameterSetNumber);
                        }
                        catch (ClassCastException e)
                        {
                                throw new Exception(String.format("%s.%s() must return a Collection of objects.", getTestClass()
                                        .getName(), getParametersMethod(getTestClass()).getName()));
                        }
                }

                @Override
                protected String getName()
                {
                        return String.format("[%s]", fParameterSetNumber);
                }

                @Override
                protected String testName(final FrameworkMethod method)
                {
                        return String.format("%s[%s]", method.getName(), fParameterSetNumber);
                }

                @Override
                protected void validateConstructor(List<Throwable> errors)
                {
                        validateOnlyOneConstructor(errors);
                }

                @Override
                protected Statement classBlock(RunNotifier notifier)
                {
                        return childrenInvoker(notifier);
                }
        }

        private List<Runner> runners = new ArrayList<Runner>();

        public ParameterizedWithBuilder(Class<?> klass) throws Throwable
        {
                super(klass, Collections.<Runner> emptyList());
                List<Object> parametersList = getParametersList(getTestClass());
                for (int i = 0; i < parametersList.size(); i++)
                        runners.add(new TestClassRunnerForParametersWithBuilder(getTestClass().getJavaClass(), parametersList, i));

        }

        @Override
        protected List<Runner> getChildren()
        {
                return runners;
        }

        @SuppressWarnings("unchecked")
        private List<Object> getParametersList(TestClass testClass) throws Throwable
        {
                return (List<Object>) getParametersMethod(testClass).invokeExplosively(null);
        }

        private FrameworkMethod getParametersMethod(TestClass testClass) throws Exception
        {
                List<FrameworkMethod> methods = testClass.getAnnotatedMethods(Parameters.class);
                for (FrameworkMethod each : methods)
                {
                        int modifiers = each.getMethod().getModifiers();
                        if (Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers))
                                return each;
                }

                throw new Exception("No public static parameters method on class " + testClass.getName());
        }

}

36 comments:

  1. Awesome! Its really remarkable piece of writing, I have got much
    clear idea concerning from this piece of writing.

    Also visit my site - genghis khan quotes

    ReplyDelete
  2. I am not sure the place you are getting your info, however great topic.

    I needs to spend some time studying more or figuring out more.

    Thanks for wonderful info I used to be looking for this info for my mission.


    Feel free to visit my web-site teddy roosevelt quotes

    ReplyDelete
  3. Pretty section of content. I just stumbled upon
    your site and in accession capital to assert that I acquire actually
    enjoyed account your blog posts. Any way I will be subscribing
    to your augment and even I achievement you access consistently quickly.



    Feel free to surf to my web page :: best quotes ever

    ReplyDelete
  4. Pretty section of content. I just stumbled upon your site and in accession capital to assert that I acquire actually enjoyed
    account your blog posts. Any way I will be subscribing to
    your augment and even I achievement you access consistently quickly.


    Also visit my site: best quotes ever

    ReplyDelete
  5. I am really enjoying the theme/design of your weblog. Do you ever run
    into any internet browser compatibility issues? A number of
    my blog audience have complained about my website not operating correctly in Explorer but looks
    great in Chrome. Do you have any solutions to help
    fix this problem?

    Feel free to visit my website - leonardo da vinci quotes

    ReplyDelete
  6. I'm really enjoying the design and layout of your blog. It's a very easy on the eyes which makes it much more pleasant for
    me to come here and visit more often. Did you hire out a
    designer to create your theme? Outstanding work!

    my web-site - self esteem quotes

    ReplyDelete
  7. Unquestionably believe that which you stated.

    Your favorite reason appeared to be on the internet the simplest thing to be aware of.
    I say to you, I definitely get irked while people consider worries that they plainly don't know about. You managed to hit the nail upon the top and defined out the whole thing without having side effect , people could take a signal. Will probably be back to get more. Thanks

    My website ... understanding quotes

    ReplyDelete
  8. My brother suggested I might like this web site.
    He was entirely right. This publish actually made my day.
    You cann't imagine just how a lot time I had spent for this information! Thank you!

    Feel free to surf to my site; rolling stones songs

    ReplyDelete
  9. You can definitely see your expertise in the article you write.
    The arena hopes for more passionate writers such as you who are not afraid to say how they believe.
    All the time go after your heart.

    My page: feelings quotes

    ReplyDelete
  10. Howdy just wanted to give you a quick heads up and let you
    know a few of the pictures aren't loading correctly. I'm not sure why but I think its a linking
    issue. I've tried it in two different internet browsers and both show the same outcome.

    Also visit my website; genghis khan quotes

    ReplyDelete
  11. You could definitely see your skills in the work you write.
    The arena hopes for more passionate writers like you who are not afraid to
    mention how they believe. At all times follow your heart.


    Here is my site william shakespeare quotes

    ReplyDelete
  12. I think the admin of this web site is truly working hard for
    his website, because here every information is quality based data.


    My site :: unusual animals

    ReplyDelete
  13. I've been exploring for a little for any high-quality articles or weblog posts on this kind of house . Exploring in Yahoo I at last stumbled upon this web site. Studying this info So i am happy to express that I have a very just right uncanny feeling I found out just what I needed. I such a lot unquestionably will make sure to do not forget this site and provides it a look regularly.

    Feel free to surf to my webpage: country flags

    ReplyDelete
  14. Hello! I could have sworn I've visited this blog before but after going through some of the articles I realized it's new to me.
    Nonetheless, I'm definitely happy I came across it and I'll be book-marking it
    and checking back frequently!

    my weblog nora ephron quotes

    ReplyDelete
  15. Your style is so unique compared to other folks I've read stuff from. Thank you for posting when you've got the opportunity, Guess I'll just book mark this web site.

    Feel free to surf to my site - understanding quotes

    ReplyDelete
  16. Wow, that's what I was exploring for, what a stuff! existing here at this web site, thanks admin of this website.

    my weblog struggle quotes

    ReplyDelete
  17. I am really glad to glance at this webpage posts which contains plenty of
    helpful facts, thanks for providing such statistics.


    My blog - thanks quotes

    ReplyDelete
  18. of course like your web site but you have to test the spelling on
    quite a few of your posts. Several of them are rife with
    spelling issues and I to find it very troublesome to inform the truth nevertheless I will definitely come again
    again.

    Also visit my webpage ... amazing quotes

    ReplyDelete
  19. Incredible! This blog looks just like my old one! It's on a totally different subject but it has pretty much the same layout and design. Excellent choice of colors!

    Also visit my weblog: john locke quotes

    ReplyDelete
  20. Spot on with this write-up, I really think this amazing site needs much more attention.
    I'll probably be returning to read more, thanks for the advice!

    Feel free to surf to my page mistake quotes

    ReplyDelete
  21. Hi my friend! I wish to say that this post is amazing, nice written and
    include almost all important infos. I'd like to peer more posts like this .

    Stop by my page - girlfriend quotes

    ReplyDelete
  22. This piece of writing is in fact a pleasant one it helps new
    web people, who are wishing for blogging.

    Also visit my page; douglas adams quotes

    ReplyDelete
  23. Great post.

    Feel free to visit my web site girlfriend quotes

    ReplyDelete
  24. May I simply say what a comfort to find an individual who really understands what they
    are talking about on the internet. You definitely know how to bring an issue to light and make it
    important. More people have to read this and understand this side
    of the story. It's surprising you're not more popular given that you certainly have the gift.


    My weblog - john locke quotes

    ReplyDelete
  25. It's an remarkable article for all the internet people; they will take benefit from it I am sure.

    Here is my webpage ... rolling stones songs

    ReplyDelete
  26. After looking at a number of the articles on your blog, I truly
    like your way of blogging. I added it to my bookmark website
    list and will be checking back soon. Take a
    look at my website as well and tell me what you think.


    Here is my webpage: frustration quotes

    ReplyDelete
  27. It's a shame you don't have a donate button! I'd definitely donate to this superb blog! I suppose for now i'll settle for
    bookmarking and adding your RSS feed to my Google
    account. I look forward to fresh updates and will talk about
    this blog with my Facebook group. Chat soon!

    Visit my web page ... kahlil gibran quotes

    ReplyDelete
  28. Nice replies in return of this issue with firm arguments and explaining the
    whole thing on the topic of that.

    Here is my web site: commitment quotes

    ReplyDelete
  29. Excellent way of explaining, and pleasant post to obtain information concerning my presentation
    topic, which i am going to deliver in university.

    Also visit my web site - zayn malik quotes

    ReplyDelete
  30. Fantastic goods from you, man. I have understand your
    stuff previous to and you're just extremely magnificent. I really like what you've acquired here, really like what you're stating and the way in which you say it. You make it enjoyable and you still take care of to keep it wise. I can't wait to read far more from you.
    This is actually a great website.

    Feel free to visit my web page - depressing quotes

    ReplyDelete
  31. Its such as you learn my mind! You appear to grasp
    a lot approximately this, like you wrote the book in it or something.
    I think that you simply could do with a few percent to pressure
    the message home a little bit, but instead of that, this is magnificent blog.
    An excellent read. I'll definitely be back.

    Feel free to visit my blog; kahlil gibran quotes

    ReplyDelete
  32. No matter if some one searches for his vital thing, thus
    he/she needs to be available that in detail, therefore that
    thing is maintained over here.

    My website ... tired quotes

    ReplyDelete
  33. I know this if off topic but I'm looking into starting my own weblog and was curious what all is needed to get setup? I'm assuming having a blog like yours would cost a pretty penny?
    I'm not very internet savvy so I'm not 100% positive. Any suggestions or advice would be greatly appreciated. Thanks

    Review my webpage :: depressing quotes

    ReplyDelete
  34. Everything is very open with a very clear explanation of the issues.
    It was truly informative. Your website is very
    helpful. Thanks for sharing!

    Here is my homepage :: unusual animals

    ReplyDelete
  35. Way cool! Some very valid points! I appreciate you penning this article
    and also the rest of the site is very good.

    Feel free to visit my website discipline quotes

    ReplyDelete
  36. Hi there would you mind sharing which blog platform you're using? I'm looking to start my own blog soon but I'm having a hard time making a decision between BlogEngine/Wordpress/B2evolution and Drupal. The reason I ask is because your design and style seems different then most blogs and I'm looking for
    something completely unique. P.
    S My apologies for being off-topic but I had to
    ask!

    Feel free to visit my site; commitment quotes

    ReplyDelete