xUnit parameters annotation based

Recently I needed to do some work on testing which requires special scenario which didn’t find quite usual, so I though that could be valuable to share with the blog readers (if any) so anyone can benefit from the code or help with better solution.

The problem

I was trying to create some infrastructure classes to be able to test with the following restrictions:

  • Execute a bunch of tests with any super class
    • Is it possible that I will need spring or any other IoC framework, so probably we will have to inherit from this.
  • Each test will have ‘n’ methods and each one can have different configuration or even we want to execute the same method with multiple parameter.
    • The different configuration will be specified at method or class level or mixed.
  • Ideally I don’t want to have to declare special constructor (which will be inherited or replicated) or special parameters on the method. The reason is because this will possibly maintained in a future by other people, so the easier to keep adding new tests the best.

What I wanted to achieve was finally something like

    @WorldWay
    @CalifornicationWay
    @BroWay
    @Test
    public void helloAllStyles() {
        System.out.println("\tProper test " + greeter.sayHello("Mum"));
    }

So that I will get an output where the test method will be executed three times each one with an specific strategy:

Proper test Hey Bro! What's up Mum?
Proper test Hello Motherfuckeer! akka Mum
Proper test Hello Mum

Options

I did consider options like junit parametrized tests or equivalent testng data providers but as a general rule causes too much couple between the infraestructure and the tests. So every time I wanted to create a new test I will have to follow some inherited rules, like have a constructor with parameters or pass the parameters on the test method itself or even remember to annotate my methods with some specific @Test(dataprovider=”something”). So I finally decided to dig a little bit more on options given by both testng & junit.

TestNG

With this framework I looked arround the different annotations and options to execute multiple times the same test method, so finally I came out with the following steps:

  • Used an annotation transformer to change the @Test annotations to become declare (in case the don’t declare another yet) an static data provider.
@Override
public void transform(ITestAnnotation annotation, Class testClass, Constructor testConstructor, Method testMethod) {
    if (interestingMethod(testMethod)) {
        if (!annotation.getDataProvider().isEmpty() || annotation.getDataProviderClass() != null) {
            if (filterUsefulAnnotations(testMethod).size() == 1) {
                // TODO make it work with data provider if there is just one annotation which we are interested in.
            }
            throw new IllegalStateException("Cannot work with data providers | provider class");
        }
        annotation.setDataProviderClass(StaticDataProvider.class);
        annotation.setDataProvider(StaticDataProvider.PROVIDER_NAME);
    }
}
  • This will instruct testng to execute the test method as many time as annotations we are really intereted in (after some playing to filter the proper annotation). To do this and not pass the parameter to the method (remember I don’t want to add a parameter to each test method) I tweaked return a list of empty objects:
    @DataProvider(name = PROVIDER_NAME)
    public static Object[][] provider(Method method, @TestInstance Object instance) {
        if (!AnnotationQueueListener.class.isAssignableFrom(instance.getClass())) {
            throw new IllegalArgumentException("Test instance must implement the proper interface");
        } else {
            Queue<Class<? extends Annotation>> annotations = AnnotationTransformer.filterUsefulAnnotations(method);

            AnnotationQueueListener initializer = (AnnotationQueueListener) instance;
            initializer.initialize(annotations);

            Object[][] result = new Object[annotations.size()][0];
            for (int i = 0; i < result.length; i++) {
                result[i] = new Object[]{};
            }
            return result;
        }
    }
  • So now we just need to tell the test which is the current strategy to use. To do this had already injected a queue of annotations on the test instance (on the previous code), which will be consumed by the test method using a @BeforeMethod method. So in the method itself we will see:
    private Queue<Class<? extends Annotation>> annotations;

    @BeforeMethod
    public void prepare(Method method) {
        greeter = createGreeting(annotations.remove());
        testName = String.format("%s_%s", method.getName(), greeter.getClass().getSimpleName());
    }

    @Override
    public void initialize(Queue<Class<? extends Annotation>> annotations) {
        this.annotations = annotations;
    }

    private Greeting createGreeting(Class<? extends Annotation> annotation) {
        if (BroWay.class.equals(annotation)) {
            return new Bro();
        } else if (CalifornicationWay.class.equals(annotation)) {
            return new Californication();
        } else if (WorldWay.class.equals(annotation)) {
            return new World();
        } else {
            throw new IllegalStateException("Could not initialize this type, your test must be annotated with TestNG @Test annotation and the ");
        }
    }

As you can see the code used to achieve this is not so complex but the result is also not so clean because we have to add on the test the logic on the before method to get the proper element withing a queue that we are not really controlling, is just part of the test instance.

This also had the bad side that the main element which expands each test method in multiple test methods is an static method, which will not easily had context and any initialization using IoC can be dangerous and more complex.

JUnit

In order to achieve this we looked arround at the options and the easiest seemed to be to use a Runner, which matches with the same approach spring used (which also is something we want to use in a future).

So to achieve this the work needed was bit more extense:

    • Create a Runner which inherits from BlockJUnit4ClassRunner which let us change the getChildren method the same way jUnit does to get the list of children in case of a parametrized test
    @Override
    protected List<FrameworkMethod> getChildren() {
        List<FrameworkMethod> children = super.getChildren();
        List<FrameworkMethod> result = new LinkedList<FrameworkMethod>();
        for (FrameworkMethod child : children) {
            for (Class<? extends Annotation> annotation : annotations) {
                prepareAnnotation(result, child, annotation);
            }
        }
        return result;
    }
    • Then on each children method we create a new FrameworkMethod where we modify the annotation the method can see (that is the key difference with TestNG because we can change the final method executed by the xUnit Framework)
    private void prepareAnnotation(List<FrameworkMethod> result, FrameworkMethod child, Class<? extends Annotation> annotationType) {
        if (child.getAnnotation(annotationType) != null) {
            result.add(cloneMethod(child.getMethod(), annotationType));
        }
    }

    private FrameworkMethod cloneMethod(Method method, final Class<? extends Annotation> toKeep) {
        return new FrameworkMethod(method){
            @Override
            public Annotation[] getAnnotations() {
                Annotation[] annotations = super.getAnnotations();
                List<Annotation> result = new LinkedList<Annotation>();
                for (Annotation annotation : annotations) {
                    if (annotation.annotationType().getAnnotation(GreetingAnnotation.class) == null ||
                            annotation.annotationType().equals(toKeep)) {
                        result.add(annotation);
                    }
                }
                return result.toArray(new Annotation[result.size()]);
            }
        };
    }
    • Finally on the test class itself we can ask the method what is its annotation because will have just one of the ones that we are intereted
    @Before
    public void before() {
        if (annotations.contains(CalifornicationWay.class)) {
            greeter = new Californication();
        } else if (annotations.contains(WorldWay.class)) {
            greeter = new World();
        } else if (annotations.contains(BroWay.class)) {
            greeter = new Bro();
        } else {
            throw new IllegalStateException("Not greeter found");
        }
    }

With this solution we still need a @Before (which can be avoided) but we don’t need any queue to keep track of which annotation should we use during method execution.

Conclusion

This let us do a solution where all tests can be just annotated and will be executed the exact number of times we are really interested in. Still some works needs to be done to clean the solution and maybe add some more proteccions but the the first implementation can be seen on my github. I’ll try to get an update on this adding some of this missing parts.

I’m a Seattle bike commuter

Yes, I have to admit I finally got it! I can say I am a bike commuter. Long time I said that I wanted to be, so finally I am a bike commuter on US … sounds strange, isn’t it? Well, turns out that is really common at least in Seattle to be a bike commuter even with the rain. But let’s start from the beginning.

Buy the baby

IMG_20140926_143554-EFFECTSAlways is complex to get something you are waiting for, specially when there are lot of options … and in terms of bikes there are a lot of options!

First, lets evaluate kind of bikes:

  • Mountain bike. As its name points out, is a bike for the mountain … It is not going to be my case, so –> Discarded! Mainly because is not so efficient.
  • Road bike. Again, is a bike for the road. They are much faster and efficient than the rest, but a bit less comfortable … finally I also discarded this one but I have to say that is a really good option for commuting, I have seen quite a lot and also seems a really good option.
  • Fixies. Are fixed-gear or what is the same you cannot stop pedaling while riding a bike like this. Most of them are also with just one gear. Seattle has a lot of hills (see the photo on the right :P), not hard but enough to discard also this option.
  • Hybrid bike. This is between mountain bike and a road bike. Some of them has suspension which makes really comfortable the drive experience and normally they have special tires to be faster. And as this is the last option, yes … this is the kind of bike I bought. Mainly because it is easier to commute with a non regular roads but efficient enough to enjoy the city.

Do I want to be the first riding this horse?

Always there is the option of second hand bikes, they are pretty good. Also there are good places in Seattle, like play it again, or  recycled bikes. But to be fair the second hand prices are not so low, even-though there are good options. As always this alternative requires time to get the proper bike. So finally I just went around to try to find the correct bike and found it in a bike shop … so there she was!

Where were you all this years?

In performance bikes. There are some shops in Seattle. The shop I went was near the University district. Was good because they give me the option to test some of the bikes inside the shop, and when I tried mine was like … there you are! It has also disk brakes which I tried in Barcelona and are really awesome plus gives you lot of security. So finally here she is:

IMG_20141002_142733

As you can see she is very nice looking! And very comfortable to ride, in fact I got surprised that didn’t hurt my a…😛 … But the saddle was really good and I don’t need any extra, not like the one I had in Barcelona.

In dimensions it is a medium frame with 700c wheels, which is similar to the 29 inches.

Price of the bike: $450 + taxes

My baby has lot of friends

Yes, I need to get lot of complements for my bike … lot of them! And you need most of them if you want to commute.

  • First of all when I got the bike the sell me also a helmet and a U lock. I need them because I was going to a dinner so I got them … then I realized that maybe was not the best but they were good enough.
    • I bought an extension for the lock … right now I have never used it, but makes me feel more secure in case I have to leave the bike for long time. And the brand is cool: Kryptonite.
  • Another important thing, which is mandatory by law, is the lights … the first night I didn’t have and some friends lend me two small ones and I understood why I need one, not just because of the law but because some streets at night are completely dark. So I went to amazon and bought a pair of lights. they are not incredible lights but good enough. I also bought a simpler ones in case of emergency or as simple extras.
  • a rain jacket days (I already used and just arrived two days ago :P). This one is good because you can remove the sleeves and has some pockets and some ventilation.
  • a rack to carry bags and panniers.
  • And a pannier, water resist and can be converted to a messenger bag and can carry a laptop.

So finally this is the current aspect of the baby:

IMG_20141023_224847:nopm:

Friends who we eventually meet

  • At some point I have to buy a waterproof trousers in case there is more rain and colder weather, which eventually can happen😛
  • a bottle for water or any liquid.
  • Maybe another pannier, in case I really need it … but right now I think I have enough space.
  • Some tools to fix the bike, but I bought an special card on the place I went that they will fix the bike in case of a flat and also tune her twice in two years, so maybe don’t need them now.
  • Water protection glasses … at least the last time was really raining I got lot of water on the eyes and I would have appreciated a glasses.
  • Front and back fender, the same day with the rain on my eyes I realized I will need this also.

The routes

Going to work on Seattle is really easy, there are some routes where you are totally safe because there is a lane, but on other roads there are signs where you should stay and cars generally respect you.

In case you are interested this is the normal route I take every day (well, almost every day) to go to work … about 20-25 mins and 5 kms (3 miles)

 

I also did one of the first days which is named burke-gilman trail. Is really good and pretty easy, to me the worst was to arrive there … and the views are spectacular (as most of Seattle landscapes).

This slideshow requires JavaScript.

 

New move! Now is time for Seattle@WA

Hello everybody,

most of you already know but I did move again, this time a little bit further, to Seattle, USA😀 (Natalie will came in some weeks, and sioux a little later).

My first time at the States, in fact the first time out of Europe at all. As usual I will start doing some posts but experiences tell me that it won’t keep the same forever😀 But being a totally different place with so many things to do and to explain and I didn’t find a blog like diariodeunlondinense. So I’ll try to give some tips (the few I find).

But let’s start from the beginning:

The trip

IMG_20140925_080204:nopm:The flight was about 3 h from Barcelona to Frankfurt and 11 h from Frankfurt to Seattle. I started at 6 am arriving to the airports (thanks Nat, Mum and Dad for bringing me there). I was a bit nervous because I was not sure about the baggage and so, but finally there was no problem, like a normal flight to London but this time to Frankfurt. By the way I got a flight with condor (first was with lufthansa and then condor itself). The first one was good, I got a really good emergency exist seat and there was some free breakfast during the plane.

IMG_20140925_111918:nopm:Then I arrived to Frankfurt where I had to wait about 4 hours. This was also my first stopover flight so I don’t know if is normal but by this time I had to go outside the security control and pass it again. During this trip I found that there were beds on the airport … I assume this is a typical airport where people has to wait a lot so it is ready, what is kind of cool!

Then I went to the business lounge … ah, maybe I forgot to tell you but was also my first time on business … as it was my first long trip I decided to give me this luxury, which in fact was not so expensive because was less in condor than getting a normal flight with other well known airlines.

10670010_10152690706729099_4223915369990816103_n

So being in the lounge at the airport is really different than being just waiting, there are food and good views of the airport, there is also drinks (as you can see just next) and good internet connection and electricity plugs for your gadgets. So I decided to relax a bit and get some “energy”!

And at that point I thought I will get normally the flight but this was the point to really present your documents, in my case with the visa in my passport was just enough. They asked me some data like where are you going to live, work and so, and that’s it (this became the most bureaucratic part of the trip).

The long flight was good overall. A bit long for me but the cabin was really good, the crew super friendly and there was plenty of food. The main meal (they served us two) was really good to be in a flight, also with good wine. The second one was with some turbulence so was a bit more difficult to enjoy it. I slept about 1 hour (maybe too excited?) and watch two movies (no-brainer movies with some action :D). The flight was in a boing 767-300 where I can get 170 degrees on my seat, with a touch screen with quite a bit movies, so was not bad … better being at home but more than acceptable.

Arrival

At the arrival I was instructed to be one of the very first on customs, so I got not extra queue. I was a bit nervous because I suppose I will got some questions and maybe some problems (I am always the positive one, don’t you notice?). I arrived probably one of the first, being in business does also helps there but there were people literally running to be some of the first because in the flight we where about 160 people and we assume there will be much more. But when we arrive we were alone in customs (and finally we were the only flight at the airport at this part of the airport … so the aiport was really empty and calm).

The customs was really fast and nothing but easy the policeman talked with me in Spanish also which was fun. Just very few questions (where are you going to stay/work) and I got the required stamp. Then wait for the luggage and end up giving a form telling what I have to declare: nothing😀

And I was ready to go! And arrived to Seattle😛

In fact I was in the Tacoma airport, not at home yet. To get to Seattle I looked around and there are shuttles (like taxis) that you can take to go anywhere from the airport and you can even share the transport so will be cheaper (around $30-40). But I though that I was not in a hurry so I wanted to took the public transport, so I did.

The first thing I did was get my orca, which is equivalent to the oyster. There was nobody to help me but a machine (in fact there was a American man who had problems and I helped him … my very first good deed). It was easy, especially compared with London or Barcelona, just some clicks. But I missed the place to touch in (orca is an RFID card so contact free but there is no control to avoid you enter, at least on the light train I took there) before going to catch the train in the upper floor, so I made a bit more exercise with my huge suitcase but was fine. After the train I took the bus, where I was a bit lost ’cause don’t even had an idea where to stop but the signs people in the house gave to me was pretty clear (and google maps also helped a bit), so finally I got to the place … a bit exhausted but all right. By the way the price of each ticket was about $2-$3, now that I took it regularly is about $2.25-2.5 (depending on the peek hour).

End of the day

Finally I got to say hello to people in the house, they are super friendly and are helping me a lot. They also told me where to get some food and I went to buy something to the supermarket … and as the day was really long and I had sinned … I got a burger at wendy’s. Then buy some food and go to sleep! (like I will do when I publish this loooong post).

 

I think this is enough for now, but keep tuned and I will try to post some other stuff … because this first days I started doing some tourist! I am getting ready for people coming to visit us😀

Meet up to know people and city

The last time I came to London (like 6 years ago) I discovered meetup.com (probably there are other alternatives but this is quite known and used), and I started using it since then to find things to do, both in Barcelona and now in London. I think this is one of the easiest way to find out what is on your city (or any city you want to visit) and meet people as well.

The first days at London was a bit of crazy trying to find out the best ones and the point is that finally I realized that every day there is at least one thing to do, so I tried to keep doing every week but not getting crazy. Now I am on some interesting meetups that maybe any of you can enjoy:

  • Scala meetup: I just have gone to two of them but they keep doing things at least once a month and some dojos as well!
  • London Java Group: It’s really active and with a lot of talks and dojos, some of them before work … they call them coffee & code, isn’t that awesome?
  • Squash meetups. Obviously I have to go to some kind of sport and now my favorite one is squash (some day I will be good at this game … maybe :D). The good point of this groups is that you can try any game they propose when they work for you, even some are free! Right now just tried once (and had another next week) but was really nice except for the fact that I am in really bad fit and I loose most of the games😛.
  • NoSQL London: I have gone to two of their meetups, mostly talks about different technologies, last one at Google Campus (in fact is named like this but is just a normal London building).

There are others I joined and some are played at SkillsMatters which is even nicer because they record all the talks that happen to be in there😀 . You can find even developers groups for specific nations. And I think Nat found that there are lot of groups for dancing Salsa and other styles.

There are some photos of events we have gone, there you can see that at most of them you can have food😛

This slideshow requires JavaScript.

 

Thanks to the London Java User Group and the London Scala User Group I know about HackTheTower which is a very nice monthly hack day organized by Salesforce’s people at the same building I am working. And as the last photo for this post there is one that I took today on this hack day with a very nice double rainbow!

2014-05-10

 

Conclusion

Meeting people in the city is the best way to learn and be in contact with the city, and also helps with language (I hardly forgot, there are a lot of language exchange groups). In fact in cities like London you can find groups for mostly everything, so have a look and tell us what you find.

I got a job!! (Nat)

Hi readers!

After 3 weeks in London, finally I got a job.
I want to explain my experience looking for a job hoping this could help someone else.
BARCELONA
I started to look for a position as senior java developer when we still were in spain. These are the steps that I followed:
  •  Updating my cv
  • Updating Linkedin’s profile
  • Contacting some recruiters (Recworks, Hydrogen, Oho group, OliverBernard…)
  • Registering in jobsite (After doing this you will receive a lot of calls of recruiters offering job opportunities)
  • Doing some phone interviews.
  • Doing some technical tests.
  • Reading the book “Cracking the code interview”, I don’t finished it but I think it is very usefull.
LONDON
  •  First week I did one scheduled face to face interview but after that I set the processes in stand by for two reasons: We were searching a flat and I didn’t had a english phone.
  • Once we had a flat and a uk sim, I notified all the recruiters that I was in London and send them my new uk phone number.
  • Everyday I reviewed the jobs opportunities in Linkedin and Jobsite and applied in the ones I thought that fits me.
As you can see, my english is not perfect, so, don’t be scared about this. If you have an intermediate level, you can tackle it.
You will realize that they always ask the same kind of questions in the interviews, so, you can prepare your answers in english.
Different types of interviews:
  •  Recruiters call (15min): They want to know a little bit about you, why you want to move, when, what role are you looking for, your current salary and your expected salary. They will also ask for your technical skills and your experience. Some of them go deeper in your cv, even some of them will ask you some basic technical questions. After the call they will send you their available job positions. Remember that you can not apply for the same company through more than one way, they have some exclusiveness policies and the company will not accept it.
  •  Technical tests(1-2h): After applying to a company they usually will send you a technical test that you can do at home as soon as possible. Be careful reading the requirements and review that your solution pass their basic tests. I think adding unit testing and a readme.txt explaining your approach is a good point, even if they don’t ask for. I did a lot of them, if the position is still open you will receive feedback very quickly.

 

  • Face to face interview(minimum 2h): If you receive a good feedback from the technical test you will be scheduled for a face to face interview. These interviews usually consist of:
  1. Introduction of the company and the role. (Do a little investigation before going to the interview)
  2. Reviewing your cv and technical skills. (be sure you can answer to any question about your cv)
  3. Questions about your technical test (not always)
  4. Programming test in situ, sometimes they let you alone, sometimes they stay besides you and ask you thinks about your approach (you can also ask).
  5. Analysis case: They explain you a case and ask you how you would solve the situation and why do you do it this way.
  6. Q&A: Time to do all the questions that you have about the role and company. (Think about it before going to the interview)
  • Technical phone interview(1h): I hate this kind of interviews, I had some of them with 2 or 3 people in the other side, asking questions like in a exam. Usually they don’t ask complicated questions but you should be prepared for it. For example, if you know that the role requires hibernate and spring, take a look to the “hibernate interview questions” and the “spring interview questions” you will find a lot of links googling that will help you. No fear to say “I don’t know”, I think is better to be honest and show your interest to learn it or show that you know something similar.
Last week I also went to get my NIN (National Insurance Number), I think it should be the first thing you can do, once you get a flat.
Follow the instructions in this link to get an appointment for the NIN interview:
They will send you the NIN in the following 4 weeks, you can work without this number, you will pay more taxes the first month but the will give you this money back once you have the NIN.
And we also got (finally) a bank account. It was not easy. Most of them ask for a proof of residence and they don’t accept the let agreement from you flat rental, they want a bill with your name and your address(something that we still didn’t received, or the NIN letter.
We found two banks that wanted to open us an account without this proof of residence, but they required that one of us had a job. Lloyds and Barclays. We did with Barclays. Note that you need an appointment to open a bank account and it will take about 1,5 hours!!
And that’s all! If you have any questions don’t hesitate to ask me😉

New flat & new job & new activities

Here we go again! Sorry for the delay but we have been really busy this week, doing tons of things, and that’s been just the first week.

On Monday we arrived to the new flat, some of you have already seen some pictures via Facebook but there are some

Tuesday: I started on the new job (incredible building named Heron Tower) and really nice offices with my Mac book pro setup with 2 extra screens, cool isn’t it? Natalie had different interviews, some of them she liked and are really near our home. There are some of the pictures of the new job, the first day I got an easter egg😀. And i went to a meetup which explained leveldb, a google nosql db mainly in memory.

This slideshow requires JavaScript.

By Natalie’s request, here it is the video of the glass based elevator which goes from the 34th floor to the ground floor in less than a minute:

Wednesday: I went to job by bike! Using barclays bikes, just 2 £ per 24 h. You can have also 7 days or all 90 £. And at the evening we went again to the Genesis Cinema to watch Spiderman 2 in 3D for 5,5 £ … with our film critic Ana :

wpid-wp-1397826065001.jpeg

Thursday: Was pre easter, so just a normal work day but after it every body went to the pub! Except us, Natalie went to a salsa place named Cuban school., and she did practice reggaeton and body isolation, she loved it! I went to my first Scala coding dojo, just went 6 people from the 70 that was supposed to came but was fun and people was very interested on new things. By the way on most of the IT meetups there is always pizza and drinks … this time was pizza for 70 people to be shared between just 6😛

Friday: Just relaxing day on our flat, also having fun with the puff we bough. At night we went to see Ana and have some fun on a proper english pub with Adai. Some new photos of the place:

This slideshow requires JavaScript.

The rest of the Easter we will do proper sightseeing at London. As you can see this days has been really busy and fun! Keep you posted.

More markets & parks

Yesterday and today has been totally kind of holiday days, you can see it on the next pictures.

This slideshow requires JavaScript.

We went to Brodway market, nice but not very big, and today we went to Brick lane market, very near to our new place and really big and nice! We’ll come back😀

Bye the way, after markets we usually go to some parks and there we do find some animals which seems being affected by Spring😛 …

But Spring is also affecting someone else :

A final suggestion in case you came to London, just visit http://www.diariodeunlondinense.com/, I has really good suggestions.