DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

The Latest Testing, Deployment, and Maintenance Topics

article thumbnail
Mock Final Method
Foreword If you already read some other blog post about unusual mocking, you can skip prelude via this link. I was asked to put together examples how to mock Java constructs well know for their testability issues: Mock private method Mock final method Mock final class Mock constructor Mock static method I am calling these techniques unusual mocking. I was worried that such examples without any guidance can be widely used by teammates not deeply experienced in mocking frameworks. Developers practicing TDD or BDD should be aware of testability problems behind these constructs and try to avoid them when designing their tests and modules. That is the reason why you probably wouldn't be facing such unusual mocking often on project using these great programming methodologies. But sometimes you have to extend or maintain legacy codebase that usually contains low cohesive classes. In most cases there isn't time in current hectic agile world to make such class easy to unit test standard way. When you are trying to unit test such class you often realize that unusual mocking is needed. That is why I decided to create and share refactoring considerations alongside with examples and workarounds for unusual mocking. Examples are using Mockito and PowerMock mocking frameworks and TestNG unit testing framework. Mock final method Refactoring considerations Change method to non-final (remove final keyword) and test it standard way. This is technique I use always when I can change code of final method. Usage of PowerMock Before usage of this example, please carefully consider if it is worth to bring bytecode manipulation risks into your project. They are gathered in this blog post. In my opinion it should be used only in very rare and non-avoidable cases. Test shows how to mock final method by PowerMock framework. Example covers: Mocking of final method with return value Mocking of final void method Verifying of final method calls Class with final methods: public class Bike { public final void shiftGear(boolean easier) { throw new UnsupportedOperationException("Fail if not mocked! [easier=" + easier + "]"); } public final int getGear() { throw new UnsupportedOperationException("Fail if not mocked!"); } } Class under test: public class Rider { private Bike bike; public Rider(Bike bike) { this.bike = bike; } public int prepareForUphill() { int gear = bike.getGear(); for (int idx = 0; idx < 2; idx++) { bike.shiftGear(true); gear++; } return gear; } } Test: @PrepareForTest(Bike.class) public class RiderTest extends PowerMockTestCase { private static final int TESTING_INITIAL_GEAR = 2; @Test public void testShiftGear() { Bike mock = PowerMockito.mock(Bike.class); Rider rider = new Rider(mock); Mockito.when(mock.getGear()).thenReturn(TESTING_INITIAL_GEAR); // invoke testing method int actualGear = rider.prepareForUphill(); Assert.assertEquals(actualGear, TESTING_INITIAL_GEAR + 2); Mockito.verify(mock, Mockito.times(2)).shiftGear(true); } } Links Source code can be downloaded from Github. Other unusual mocking examples: Mock private method Mock final class Mock constructor Mock static method
April 12, 2014
by Lubos Krnac
· 27,186 Views · 18 Likes
article thumbnail
Be a Lazy But Productive Android Developer, Part 5: Image Loading Library
Welcome to part 5 of “Be a lazy but a productive android developer” series. If you are a lazy Android developer and looking for image loading library, which could help you to load image(s) asynchronously without writing a logic for downloading and caching images then this article is for you. This series so far: Part 1: We looked at RoboGuice, a dependency injection library by which we can reduce the boiler plate code, save time and there by achieve productivity during Android app development. Part 2: We saw and explored about Genymotion, which is a rocket speed emulator and super-fast emulator as compared to native emulator. And we can use Genymotion while developing apps and can quickly test apps and there by can achieve productivity. Part 3: We understood and explored about JSON Parsing libraries (GSON and Jackson), using which we can increase app performance, we can decrease boilerplate code and there by can optimize productivity. Part 4: We talked about Card UI and explored card library, also created a basic card and simple card list demo. In this part In this part, we are going to talk about some image libraries using which we can load image(s) asynchronously, can cache images and also can download images into the local storage. Required features for loading images Almost every android app has a need to load remote images. While loading remote images, we have to take care of below things: Image loading process must be done in background (i.e. asynchronously) to avoid blocking UI main thread. Image recycling image should be done. Image should be displayed once its loaded successfully. Images should be cached in local memory for the later use. If remote image gets failed (due to network connection or bad url or any other reasons) to load then it should be managed perfectly for avoiding duplicate requests to load the same again, instead it should load if and only if net connection is available. Memory management should be done efficiently. In short, we have to write a code to manage each and every aspects of image loading but there are some awesome libraries available, using which we can load/download image asynchronously. We just have to call the load image method and success/failure callbacks. Asynchronous image loading Consider a case where we are having 50 images and 50 titles and we try to load all the images/text into the listview, it won’t display anything until all the images get downloaded. Here Asynchronous image loading process comes in picture. Asynchronous image loading is nothing but a loading process which happens in background so that it doesn’t block main UI thread and let user to play with other loaded data on the screen. Images will be getting displayed as and when it gets downloaded from background threads. Asynchronous image loading libraries Nostra’s Universal Image loader – https://github.com/nostra13/Android-Universal-Image-Loader Picasso – http://square.github.io/picasso/ UrlImageViewHelper by Koush Volley - By Android team members @ Google Novoda’s Image loader – https://github.com/novoda/ImageLoader Let’s have a look at examples using Picasso and Universal Image loader libraries. Example 1: Nostra’s Universal Image loader Step 1: Initialize ImageLoader configuration ? public class MyApplication extends Application{ @Override public void onCreate() { // TODO Auto-generated method stub super.onCreate(); // Create global configuration and initialize ImageLoader with this configuration ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext()).build(); ImageLoader.getInstance().init(config); } } Step 2: Declare application class inside Application tag in AndroidManifest.xml file ? Step 3: Load image and display into ImageView ? ImageLoader.getInstance().displayImage(objVideo.getThumb(), holder.imgVideo); Now, Universal Image loader also provides a functionality to implement success/failure callback to check whether image loading is failed or successful. ? ImageLoader.getInstance().displayImage(photoUrl, imgView, new ImageLoadingListener() { @Override public void onLoadingStarted(String arg0, View arg1) { // TODO Auto-generated method stub findViewById(R.id.EL3002).setVisibility(View.VISIBLE); } @Override public void onLoadingFailed(String arg0, View arg1, FailReason arg2) { // TODO Auto-generated method stub findViewById(R.id.EL3002).setVisibility(View.GONE); } @Override public void onLoadingComplete(String arg0, View arg1, Bitmap arg2) { // TODO Auto-generated method stub findViewById(R.id.EL3002).setVisibility(View.GONE); } @Override public void onLoadingCancelled(String arg0, View arg1) { // TODO Auto-generated method stub findViewById(R.id.EL3002).setVisibility(View.GONE); } }); Example 2: Picasso Image loading straight way: ? Picasso.with(context).load("http://postimg.org/image/wjidfl5pd/").into(imageView); Image re-sizing: ? Picasso.with(context) .load(imageUrl) .resize(100, 100) .centerCrop() .into(imageView) Example 3: UrlImageViewHelper library It’s an android library that sets an ImageView’s contents from a url, manages image downloading, caching, and makes your coffee too. UrlImageViewHelper will automatically download and manage all the web images and ImageViews. Duplicate urls will not be loaded into memory twice. Bitmap memory is managed by using a weak reference hash table, so as soon as the image is no longer used by you, it will be garbage collected automatically. Image loading straight way: ? UrlImageViewHelper.setUrlDrawable(imgView, "http://yourwebsite.com/image.png"); Placeholder image when image is being downloaded: ? UrlImageViewHelper.setUrlDrawable(imgView, "http://yourwebsite.com/image.png", R.drawable.loadingPlaceHolder); Cache images for a minute only: ? UrlImageViewHelper.setUrlDrawable(imgView, "http://yourwebsite.com/image.png", null, 60000); Example 4: Volley library Yes Volley is a library developed and being managed by some android team members at Google, it was announced by Ficus Kirkpatrick during the last I/O. I wrote an article about Volley library 10 months back , read it and give it a try if you haven’t used it yet. Let’s look at an example of image loading using Volley. Step 1: Take a NetworkImageView inside your xml layout. ? Step 2: Define a ImageCache class Yes you are reading title perfectly, we have to define an ImageCache class for initializing ImageLoader object. ? public class BitmapLruCache extends LruCache implements ImageLoader.ImageCache { public BitmapLruCache() { this(getDefaultLruCacheSize()); } public BitmapLruCache(int sizeInKiloBytes) { super(sizeInKiloBytes); } @Override protected int sizeOf(String key, Bitmap value) { return value.getRowBytes() * value.getHeight() / 1024; } @Override public Bitmap getBitmap(String url) { return get(url); } @Override public void putBitmap(String url, Bitmap bitmap) { put(url, bitmap); } public static int getDefaultLruCacheSize() { final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024); final int cacheSize = maxMemory / 8; return cacheSize; } } Step 3: Create an ImageLoader object and load image Create an ImageLoader object and initialize it with ImageCache object and RequestQueue object. ? ImageLoader.ImageCache imageCache = new BitmapLruCache(); ImageLoader imageLoader = new ImageLoader(Volley.newRequestQueue(context), imageCache); Step 4: Load an image into ImageView ? NetworkImageView imgAvatar = (NetworkImageView) findViewById(R.id.imgDemo); imageView.setImageUrl(url, imageLoader); Which library to use? Can you decide which library you would use? Let us know which and what are the reasons? Selection of the library is always depends on the requirement. Let’s look at the few fact points about each library so that you would able to compare exactly and can take decision. Picasso: It’s just a one liner code to load image using Picasso. No need to initialize ImageLoader and to prepare a singleton instance of image loader. Picasso allows you to specify exact target image size. It’s useful when you have memory pressure or performance issues, you can trade off some image quality for speed. Picasso doesn’t provide a way to prepare and store thumbnails of local images. Sometimes you need to check image loading process is in which state, loading, finished execution, failed or cancelled image loading. Surprisingly It doesn’t provide a callback functionality to check any state. “fetch()” dose not pass back anything. “get()” is for synchronously read, and “load()” is for asynchronously draw a view. Universal Image loader (UIL): It’s the most popular image loading library out there. Actually, it’s based on the Fedor Vlasov’s project which was again probably a very first complete solution and also a most voted answer (for the image loading solution) on Stackoverflow. UIL library is better in documentation and even there’s a demo example which highlights almost all the features. UIL provides an easy way to download image. UIL uses builders for customization. Almost everything can be configured. UIL doesn’t not provide a way to specify image size directly you want to load into a view. It uses some rules based on the size of the view. Indirectly you can do it by mentioning ImageSize argument in the source code and bypass the view size checking. It’s not as flexible as Picasso. Volley: It’s officially by Android dev team, Google but still it’s not documented. It’s just not an image loading library only but an asynchronous networking library Developer has to define ImageCache class their self and has to initialize ImageLoader object with RequestQueue and ImageCache objects. So now I am sure now you can be able to compare libraries. Choosing library is a bit difficult talk because it always depends on the requirement and type of projects. If the project is large then you should go for Picasso or Universal Image loader. If the project is small then you can consider to use Volley librar, because Volley isn’t an image loading library only but it tries to solve a more generic solution.). I suggest you to start with Picasso. If you want more control and customization, go for UIL. Read more: http://blog.bignerdranch.com/3177-solving-the-android-image-loading-problem-volley-vs-picasso/ http://stackoverflow.com/questions/19995007/local-image-caching-solution-for-android-square-picasso-vs-universal-image-load https://plus.google.com/103583939320326217147/posts/bfAFC5YZ3mq Hope you liked this part of “Lazy android developer: Be productive” series. Till the next part, keep exploring image loading libraries mentioned above and enjoy!
April 11, 2014
by Paresh Mayani
· 63,973 Views · 2 Likes
article thumbnail
Comparing Quartz, cron4j and Obsidian Scheduler
We’ve all worked on projects that required us to do very basic tasks at periodic intervals. Perhaps we chose a basic ScheduledThreadPoolExecutor. If we’re already using Spring, maybe we tried their TaskExecutor/TaskScheduler support. But once we encounter any number of situations such as an increased quantity of tasks, new interdependencies between tasks, unexpected problems in task execution or the like, we will likely start to consider a more extensive scheduling solution. Our website has a fairly exhaustive feature comparison of the most commonly used Java schedulers, so we won’t go into that in this post, but we do encourage you to take a look. Features aside, are there other criteria that should come into play? Factors such as development team responsiveness to feature requests and bug reports certainly can be critical for many organizations. If you head over to the Quartz Download page, you’ll see that they haven’t had a release in over a year, despite there being many active unresolved issues.Cron4j hasn’t had a release in over 2 years. While Spring has made some changes to the design of their TaskExecutor/TaskScheduler support in recent releases, their true priorities lie elsewhere as they have not really done much to expand the feature set. Obsidian Scheduler on the other hand is actively maintained, actively supported (with free online support!) and responsive to our user community. In the past year, we’ve averaged a release per month delivering a blend of features, enhancements and fixes, proof that we’re a nimble and responsive organization. We encourage you to give Obsidian a try today!
April 11, 2014
by Craig Flichel
· 13,533 Views
article thumbnail
Be a Lazy but a Productive Android Developer, Part 4: Card UI
Welcome to part 4 of the “Be a lazy but a productive android developer” series. If you are lazy android developers for creating row items for ListView/GridView but would want to create an awesome ListView/GridView in easy steps then this article is for you. This series so far: Part 1: We looked at RoboGuice, a dependency injection library by which we can reduce the boiler plate code, save time and there by achieve productivity during Android app development. Part 2: We saw and explored about Genymotion, which is a rocket speed emulator and super-fast emulator as compared to native emulator. And we can use Genymotion while developing apps and can quickly test apps and there by can achieve productivity. Part 3: We understood and explored about JSON Parsing libraries (GSON and Jackson), using which we can increase app performance, we can decrease boilerplate code and there by can optimize productivity. In this Part In this part, we are going to explore 2-3 card UI libraries which are open source and available on GitHub and we can use either of it into our app development to have a quick listview/gridview with awesome card view. What is Card UI and Why Should We Follow Card UI Design? Ever wondered about Google play store UI which is built around cards. Card is nothing but a single row item of ListView or GridView. As depicted below, card can be of various sizes and can be either app card, movie, books, games or app suggestions card or birthday card or even it can be a simple list/grid item too. The main benefit of designing app with card UI is it gives consistent looks throughout the application, doesn’t matter whether it gets loaded in mobile or tablet. Cards Libraries Now, I am sure you are excited to read and explore about cards libraries existed on web. As I said, Google play store UI is built around card, we can build the same card UI either defining our own custom adapter with styles/images or we can achieve this type of card UI directly by using some open-source card libraries. I am sure you are lazy android developer but want to be a productive developer so you would go for using card UI library Regarding card library, it just provides an easy way to display card UIs in your android app. I have found 3 widely used card libraries in android development: Cardslib by Gabriele MariottiGabriele Mariotti – https://github.com/gabrielemariotti/cardslib Cards UI by Aidan Follestad – https://github.com/afollestad/Cards-UI CardsUI by Nadavfima – https://github.com/nadavfima/cardsui-for-android Being a lazy but a productive android developer, so far I have used Cardslib by Gabriele. As far as I have used Cardslib, I would say you don’t need to define a row layout or custom adapter to display simple card list, but yes you would have to design custom xml layout in case if you would want to customize card layout as per your designs and requirements. I would recommend Cardslib by Gabriele because it’s very well documented and is being improved actively. He has been putting a lot of effort to include new stuffs into the library like he recently included a support for preparing staggered grid with cards. How to Use Cardslib? Cardslib is available as a separate library project so you can reference it as a local library. It’s also pushed as a AAR tp Maven Central. Read detailed instructions regarding How to include, build or reference cardlib. Example 1: Simple Card UI Example To give demo, currently I have used eclipse so I have downloaded cardslib library project and will be referencing into our example projects. Let’s develop a simple card view example using 1st library listed above. row_card.xml Java code to set row_card xml layout, set title, header, image, etc. // Create a Card Card card = new Card(this, R.layout.row_card); // Create a CardHeader CardHeader header = new CardHeader(this); header.setTitle("Hello world"); card.setTitle("Simple card demo"); CardThumbnail thumb = new CardThumbnail(this); thumb.setDrawableResource(R.drawable.ic_launcher); card.addCardThumbnail(thumb); // Add Header to card card.addCardHeader(header); // Set card in the cardView CardView cardView = (CardView) findViewById(R.id.carddemo); cardView.setCard(card); Example 2: Card list example activity_list.xml CardListActivity.java package com.technotalkative.cardslibdemo; import it.gmariotti.cardslib.library.internal.Card; import it.gmariotti.cardslib.library.internal.CardArrayAdapter; import it.gmariotti.cardslib.library.internal.CardHeader; import it.gmariotti.cardslib.library.internal.CardThumbnail; import it.gmariotti.cardslib.library.view.CardListView; import java.util.ArrayList; import android.app.Activity; import android.os.Bundle; public class CardListActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.activity_list); int listImages[] = new int[]{R.drawable.angry_1, R.drawable.angry_2, R.drawable.angry_3, R.drawable.angry_4, R.drawable.angry_5}; ArrayList cards = new ArrayList(); for (int i = 0; i<5; i++) { // Create a Card Card card = new Card(this); // Create a CardHeader CardHeader header = new CardHeader(this); // Add Header to card header.setTitle("Angry bird: " + i); card.setTitle("sample title"); card.addCardHeader(header); CardThumbnail thumb = new CardThumbnail(this); thumb.setDrawableResource(listImages[i]); card.addCardThumbnail(thumb); cards.add(card); } CardArrayAdapter mCardArrayAdapter = new CardArrayAdapter(this, cards); CardListView listView = (CardListView) this.findViewById(R.id.myList); if (listView != null) { listView.setAdapter(mCardArrayAdapter); } } } Download Source Code You can download source code of above examples from here: https://github.com/PareshMayani/CardslibDemo. To run this example, first you have to download library project and then reference it into our example. Above were just simple examples, if you explore card library then you would be able to understand usage of it and would be able to reduce boiler plate code by not writing adapter/layout code again and there by would be able optimize productivity. Hope you liked this part of “Lazy android developer: Be productive” series. Till the next part, keep building card UI, card list, card grid and enjoy!
April 10, 2014
by Paresh Mayani
· 57,907 Views
article thumbnail
A Docker ‘Hello World' With Mono
Docker is a lightweight virtualization technology for Linux that promises to revolutionize the deployment and management of distributed applications. Rather than requiring a complete operating system, like a traditional virtual machine, Docker is built on top of Linux containers, a feature of the Linux kernel, that allows light-weight Docker containers to share a common kernel while isolating applications and their dependencies. There’s a very good Docker SlideShare presentation here that explains the philosophy behind Docker using the analogy of standardized shipping containers. Interesting that the standard shipping container has done more to create our global economy than all the free-trade treaties and international agreements put together. A Docker image is built from a script, called a ‘Dockerfile’. Each Dockerfile starts by declaring a parent image. This is very cool, because it means that you can build up your infrastructure from a layer of images, starting with general, platform images and then layering successively more application specific images on top. I’m going to demonstrate this by first building an image that provides a Mono development environment, and then creating a simple ‘Hello World’ console application image that runs on top of it. Because the Dockerfiles are simple text files, you can keep them under source control and version your environment and dependencies alongside the actual source code of your software. This is a game changer for the deployment and management of distributed systems. Imagine developing an upgrade to your software that includes new versions of its dependencies, including pieces that we’ve traditionally considered the realm of the environment, and not something that you would normally put in your source repository, like the Mono version that the software runs on for example. You can script all these changes in your Dockerfile, test the new container on your local machine, then simply move the image to test and then production. The possibilities for vastly simplified deployment workflows are obvious. Docker brings concerns that were previously the responsibility of an organization’s operations department and makes them a first class part of the software development lifecycle. Now your infrastructure can be maintained as source code, built as part of your CI cycle and continuously deployed, just like the software that runs inside it. Docker also provides docker index, an online repository of docker images. Anyone can create an image and add it to the index and there are already images for almost any piece of infrastructure you can imagine. Say you want to use RabbitMQ, all you have to do is grab a handy RabbitMQ images such as https://index.docker.io/u/tutum/rabbitmq/ and run it like this: docker run -d -p 5672:5672 -p 55672:55672 tutum/rabbitmq The –p flag maps ports between the image and the host. Let’s look at an example. I’m going to show you how to create a docker image for the Mono development environment and have it built and hosted on the docker index. Then I’m going to build a local docker image for a simple ‘hello world’ console application that I can run on my Ubuntu box. First we need to create a Docker file for our Mono environment. I’m going to use the Mono debian packages from directhex. These are maintained by the official Debian/Ubuntu Mono team and are the recommended way of installing the latest Mono versions on Ubuntu. Here’s the Dockerfile: #DOCKER-VERSION 0.9.1 # #VERSION 0.1 # # monoxide mono-devel package on Ubuntu 13.10 FROM ubuntu:13.10 MAINTAINER Mike Hadlow RUN sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -q software-properties-common RUN sudo add-apt-repository ppa:directhex/monoxide -y RUN sudo apt-get update RUN sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -q mono-devel Notice the first line (after the comments) that reads, ‘FROM ubuntu:13.10’. This specifies the parent image for this Dockerfile. This is the official docker Ubuntu image from the index. When I build this Dockerfile, that image will be automatically downloaded and used as the starting point for my image. But I don’t want to build this image locally. Docker provide a build server linked to the docker index. All you have to do is create a public GitHub repository containing your dockerfile, then link the repository to your profile on docker index. You can read the documentation for the details. The GitHub repository for my Mono image is at https://github.com/mikehadlow/ubuntu-monoxide-mono-devel. Notice how the Docker file is in the root of the repository. That’s the default location, but you can have multiple files in sub-directories if you want to support many images from a single repository. Now any time I push a change of my Dockerfile to GitHub, the docker build system will automatically build the image and update the docker index. You can see image listed here:https://index.docker.io/u/mikehadlow/ubuntu-monoxide-mono-devel/ I can now grab my image and run it interactively like this: $ sudo docker pull mikehadlow/ubuntu-monoxide-mono-devel Pulling repository mikehadlow/ubuntu-monoxide-mono-devel f259e029fcdd: Download complete 511136ea3c5a: Download complete 1c7f181e78b9: Download complete 9f676bd305a4: Download complete ce647670fde1: Download complete d6c54574173f: Download complete 6bcad8583de3: Download complete e82d34a742ff: Download complete $ sudo docker run -i mikehadlow/ubuntu-monoxide-mono-devel /bin/bash mono --version Mono JIT compiler version 3.2.8 (Debian 3.2.8+dfsg-1~pre1) Copyright (C) 2002-2014 Novell, Inc, Xamarin Inc and Contributors. www.mono-project.com TLS: __thread SIGSEGV: altstack Notifications: epoll Architecture: amd64 Disabled: none Misc: softdebug LLVM: supported, not enabled. GC: sgen exit Next let’s create a new local Dockerfile that compiles a simple ‘hello world’ program, and then runs it when we run the image. You can follow along with these steps. All you need is a Ubuntu machine with Docker installed. First here’s our ‘hello world’, save this code in a file named hello.cs: using System; namespace Mike.MonoTest { public class Program { public static void Main() { Console.WriteLine("Hello World"); } } } Next we’ll create our Dockerfile. Copy this code into a file called ‘Dockerfile’: #DOCKER-VERSION 0.9.1 FROM mikehadlow/ubuntu-monoxide-mono-devel ADD . /src RUN mcs /src/hello.cs CMD ["mono", "/src/hello.exe"] Once again, notice the ‘FROM’ line. This time we’re telling Docker to start with our mono image. The next line ‘ADD . /src’, tells Docker to copy the contents of the current directory (the one containing our Dockerfile) into a root directory named ‘src’ in the container. Now our hello.cs file is at /src/hello.cs in the container, so we can compile it with the mono C# compiler, mcs, which is the line ‘RUN mcs /src/hello.cs’. Now we will have the executable, hello.exe, in the src directory. The line ‘CMD [“mono”, “/src/hello.exe”]’ tells Docker what we want to happen when the container is run: just execute our hello.exe program. As an aside, this exercise highlights some questions around what best practice should be with Docker. We could have done this in several different ways. Should we build our software independently of the Docker build in some CI environment, or does it make sense to do it this way, with the Docker build as a step in our CI process? Do we want to rebuild our container for every commit to our software, or do we want the running container to pull the latest from our build output? Initially I’m quite attracted to the idea of building the image as part of the CI but I expect that we’ll have to wait a while for best practice to evolve. Anyway, for now let’s manually build our image: $ sudo docker build -t hello . Uploading context 1.684 MB Uploading context Step 0 : FROM mikehadlow/ubuntu-monoxide-mono-devel ---> f259e029fcdd Step 1 : ADD . /src ---> 6075dee41003 Step 2 : RUN mcs /src/hello.cs ---> Running in 60a3582ab6a3 ---> 0e102c1e4f26 Step 3 : CMD ["mono", "/src/hello.exe"] ---> Running in 3f75e540219a ---> 1150949428b2 Successfully built 1150949428b2 Removing intermediate container 88d2d28f12ab Removing intermediate container 60a3582ab6a3 Removing intermediate container 3f75e540219a You can see Docker executing each build step in turn and storing the intermediate result until the final image is created. Because we used the tag (-t) option and named our image ‘hello’, we can see it when we list all the docker images: $ sudo docker images REPOSITORY TAG IMAGE ID CREATED VIRTUAL SIZE hello latest 1150949428b2 10 seconds ago 396.4 MB mikehadlow/ubuntu-monoxide-mono-devel latest f259e029fcdd 24 hours ago 394.7 MB ubuntu 13.10 9f676bd305a4 8 weeks ago 178 MB ubuntu saucy 9f676bd305a4 8 weeks ago 178 MB ... Now let’s run our image. The first time we do this Docker will create a container and run it. Each subsequent run will reuse that container: $ sudo docker run hello Hello World And that’s it. Imagine that instead of our little hello.exe, this image contained our web application, or maybe a service in some distributed software. In order to deploy it, we’d simply ask Docker to run it on any server we like; development, test, production, or on many servers in a web farm. This is an incredibly powerful way of doing consistent repeatable deployments. To reiterate, I think Docker is a game changer for large server side software. It’s one of the most exciting developments to have emerged this year and definitely worth your time to check out.
April 3, 2014
by Mike Hadlow
· 11,309 Views
article thumbnail
Multi-Level Argparse in Python (Parsing Commands Like Git)
It’s a common pattern for command line tools to have multiple subcommands that run off of a single executable. For example, git fetch origin and git commit --amend both use the same executable /usr/bin/git to run. Each subcommand has its own set of required and optional parameters. This pattern is fairly easy to implement in your own Python command-line utilities using argparse. Here is a script that pretends to be git and provides the above two commands and arguments. #!/usr/bin/env python import argparse import sys class FakeGit(object): def __init__(self): parser = argparse.ArgumentParser( description='Pretends to be git', usage='''git [] The most commonly used git commands are: commit Record changes to the repository fetch Download objects and refs from another repository ''') parser.add_argument('command', help='Subcommand to run') # parse_args defaults to [1:] for args, but you need to # exclude the rest of the args too, or validation will fail args = parser.parse_args(sys.argv[1:2]) if not hasattr(self, args.command): print 'Unrecognized command' parser.print_help() exit(1) # use dispatch pattern to invoke method with same name getattr(self, args.command)() def commit(self): parser = argparse.ArgumentParser( description='Record changes to the repository') # prefixing the argument with -- means it's optional parser.add_argument('--amend', action='store_true') # now that we're inside a subcommand, ignore the first # TWO argvs, ie the command (git) and the subcommand (commit) args = parser.parse_args(sys.argv[2:]) print 'Running git commit, amend=%s' % args.amend def fetch(self): parser = argparse.ArgumentParser( description='Download objects and refs from another repository') # NOT prefixing the argument with -- means it's not optional parser.add_argument('repository') args = parser.parse_args(sys.argv[2:]) print 'Running git fetch, repository=%s' % args.repository if __name__ == '__main__': FakeGit() The argparse library gives you all kinds of great stuff. You can run ./git.py --help and get the following: usage: git [] The most commonly used git commands are: commit Record changes to the repository fetch Download objects and refs from another repository Pretends to be git positional arguments: command Subcommand to run optional arguments: -h, --help show this help message and exit You can get help on a particular subcommand with ./git.py commit --help. usage: git.py [-h] [--amend] Record changes to the repository optional arguments: -h, --help show this help message and exit --amend Want bash completion on your awesome new command line utlity? Try argcomplete, a drop in bash completion for Python + argparse.
April 3, 2014
by Chase Seibert
· 18,197 Views · 1 Like
article thumbnail
Be a Lazy but Productive Android Developer, Part 3: JSON Parsing Library
If you are lazy Android developers for JSON parsing but want to be a productive by using JSON parsing library then this article is for you.
April 2, 2014
by Paresh Mayani
· 83,245 Views · 1 Like
article thumbnail
Docker: Bulk Remove Images and Containers
I’ve just started looking at Docker. It’s a cool new technology that has the potential to make the management and deployment of distributed applications a great deal easier. I’d very much recommend checking it out. I’m especially interested in using it to deploy Mono applications because it promises to remove the hassle of deploying and maintaining the mono runtime on a multitude of Linux servers. I’ve been playing around creating new images and containers and debugging my Dockerfile, and I’ve wound up with lots of temporary containers and images. It’s really tedious repeatedly running ‘docker rm’ and ‘docker rmi’, so I’ve knocked up a couple of bash commands to bulk delete images and containers. Delete all containers: sudo docker ps -a -q | xargs -n 1 -I {} sudo docker rm {} Delete all un-tagged (or intermediate) images: sudo docker rmi $( sudo docker images | grep '' | tr -s ' ' | cut -d ' ' -f 3)
April 2, 2014
by Mike Hadlow
· 14,622 Views
article thumbnail
How To Add Images To A GitHub Wiki
Every GitHub repository comes with its own wiki. This is a great place to put the documentation for your project. What isn’t clear from the wiki documentation is how to add images to your wiki. Here’s my step-by-step guide. I’m going to add a logo to the main page of my WikiDemo repository’s wiki: https://github.com/mikehadlow/WikiDemo/wiki/Main-Page First clone the wiki. You grab the clone URL from the button at the top of the wiki page. $ git clone [email protected]:mikehadlow/WikiDemo.wiki.git Cloning into 'WikiDemo.wiki'... Enter passphrase for key '/home/mike.hadlow/.ssh/id_rsa': remote: Counting objects: 6, done. remote: Compressing objects: 100% (3/3), done. remote: Total 6 (delta 0), reused 0 (delta 0) Receiving objects: 100% (6/6), done. Create a new directory called ‘images’ (it doesn’t matter what you call it, this is just a convention I use): $ mkdir images Then copy your picture(s) into the images directory (I’ve copied my logo_design.png file to my images directory). $ ls -l -rwxr-xr-x 1 mike.hadlow Domain Users 12971 Sep 5 2013 logo_design.png Commit your changes and push back to GitHub: $ git add -A $ git status # On branch master # Changes to be committed: # (use "git reset HEAD ..." to unstage) # # new file: images/logo_design.png # $ git commit -m "Added logo_design.png" [master 23a1b4a] Added logo_design.png 1 files changed, 0 insertions(+), 0 deletions(-) create mode 100755 images/logo_design.png $ git push Enter passphrase for key '/home/mike.hadlow/.ssh/id_rsa': Counting objects: 5, done. Delta compression using up to 4 threads. Compressing objects: 100% (3/3), done. Writing objects: 100% (4/4), 9.05 KiB, done. Total 4 (delta 0), reused 0 (delta 0) To [email protected]:mikehadlow/WikiDemo.wiki.git 333a516..23a1b4a master -> master Now we can put a link to our image in ‘Main Page’: Save and there’s your image for all to see:
March 27, 2014
by Mike Hadlow
· 25,432 Views · 1 Like
article thumbnail
Integration Testing for Spring Applications with JNDI Connection Pools
We all know we need to use connection pools where ever we connect to a database. All of the modern drivers using JDBC type 4 support it. In this post we will have look at an overview ofconnection pooling in spring applications and how to deal with same context in a non JEE enviorements (like tests). Most examples of connecting to database in spring is done using DriverManagerDataSource. If you don't read the documentation properly then you are going to miss a very important point. NOTE: This class is not an actual connection pool; it does not actually pool Connections. It just serves as simple replacement for a full-blown connection pool, implementing the same standard interface, but creating new Connections on every call. Useful for test or standalone environments outside of a J2EE container, either as a DataSource bean in a corresponding ApplicationContext or in conjunction with a simple JNDI environment. Pool-assuming Connection.close() calls will simply close the Connection, so any DataSource-aware persistence code should work. Yes, by default the spring applications does not use pooled connections. There are two ways to implement the connection pooling. Depending on who is managing the pool. If you are running in a JEE environment, then it is prefered use the container for it. In a non-JEE setup there are libraries which will help the application to manage the connection pools. Lets discuss them in bit detail below. 1. Server (Container) managed connection pool (Using JNDI) When the application connects to the database server, establishing the physical actual connection takes much more than the execution of the scripts. Connection pooling is a technique that was pioneered by database vendors to allow multiple clients to share a cached set of connection objects that provide access to a database resource. The JavaWorld article gives a good overview about this. In a J2EE container, it is recommended to use a JNDI DataSource provided by the container. Such a DataSource can be exposed as a DataSource bean in a Spring ApplicationContext via JndiObjectFactoryBean, for seamless switching to and from a local DataSource bean like this class. The below articles helped me in setting up the data source in JBoss AS. 1. DebaJava Post 2. JBoss Installation Guide 3. JBoss Wiki Next step is to use these connections created by the server from the application. As mentioned in the documentation you can use the JndiObjectFactoryBean for this. It is as simple as below If you want to write any tests using springs "SpringJUnit4ClassRunner" it can't load the context becuase the JNDI resource will not be available. For tests, you can then either set up a mock JNDI environment through Spring's SimpleNamingContextBuilder, or switch the bean definition to a local DataSource (which is simpler and thus recommended). As I was looking for a good solutions to this problem (I did not want a separate context for tests) this SO answer helped me. It sort of uses the various tips given in the Javadoc to good effect. The issue with the above solution is the repetition of code to create the JNDI connections. I have solved it using a customized runner SpringWithJNDIRunner. This class adds the JNDI capabilities to the SpringJUnit4ClassRunner. It reads the data source from "test-datasource.xml" file in the class path and binds it to the JNDI resource with name "java:/my-ds". After the execution of this code the JNDI resource is available for the spring container to consume. import javax.naming.NamingException; import org.junit.runners.model.InitializationError; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.mock.jndi.SimpleNamingContextBuilder; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * This class adds the JNDI capabilities to the SpringJUnit4ClassRunner. * @author mkadicha * */ public class SpringWithJNDIRunner extends SpringJUnit4ClassRunner { public static boolean isJNDIactive; /** * JNDI is activated with this constructor. * * @param klass * @throws InitializationError * @throws NamingException * @throws IllegalStateException */ public SpringWithJNDIRunner(Class klass) throws InitializationError, IllegalStateException, NamingException { super(klass); synchronized (SpringWithJNDIRunner.class) { if (!isJNDIactive) { ApplicationContext applicationContext = new ClassPathXmlApplicationContext( "test-datasource.xml"); SimpleNamingContextBuilder builder = new SimpleNamingContextBuilder(); builder.bind("java:/my-ds", applicationContext.getBean("dataSource")); builder.activate(); isJNDIactive = true; } } } } To use this runner you just need to use the annotation @RunWith(SpringWithJNDIRunner.class) in your test. This class extends SpringJUnit4ClassRunner beacuse a there can only be one class in the @RunWith annotation. The JNDI is created only once is a test cycle. This class provides a clean solution to the problem. 2. Application managed connection pool If you need a "real" connection pool outside of a J2EE container, consider Apache's Jakarta Commons DBCP or C3P0. Commons DBCP's BasicDataSource and C3P0's ComboPooledDataSource are full connection pool beans, supporting the same basic properties as this class plus specific settings (such as minimal/maximal pool size etc). Below user guides can help you configure this. 1. Spring Docs 2. C3P0 Userguide 3. DBCP Userguide The below articles speaks about the general guidelines and best practices in configuring the connection pools. 1. SO question on Spring JDBC Connection pools 2. Connection pool max size in MS SQL Server 2008 3. How to decide the max number of connections 4. Monitoring the number of active connections in SQL Server 2008 Note:- All the text in italics are copied from the spring documentation of the DriverManagerDataSource.
March 26, 2014
by Manu Pk
· 25,265 Views · 1 Like
article thumbnail
Distributed Counters Feature Design
this is another experiment with longer posts. previously, i used the time series example as the bed on which to test some ideas regarding feature design, to explain how we work and in general work out the rough patches along the way. i should probably note that these posts are purely fiction at this point. we have no plans to include a time series feature in ravendb at this time. i am trying to work out some thoughts in the open and get your feedback. at any rate, yesterday we had a request for cassandra style counters at the mailing list. and as long as i am doing feature design series, i thought that i could talk about how i would go about implementing this. again, consider this fiction, i have no plans of implementing this at this time. the essence of what we want is to be able to… count stuff. efficiently, in a distributed manner, with optional support for cross data center replication. very roughly, the idea is to have “sub counters”, unique for every node in the system. whenever you increment the value, we log this to our own sub counter, and then replicate it out. whenever you read it, we just sum all the data we have from all the sub counters. let us outline the various parts of the solution in the same order as the one i used for time series. storage a counter is just a named 64 bits signed integer. a counter name can be any string up to 128 printable characters. the external interface of the storage would look like this: 1: public struct counterincrement 2: { 3: public string name; 4: public long change; 5: } 6: 7: public struct counter 8: { 9: public string name; 10: public string source; 11: public long value; 12: } 13: 14: public interface icounterstorage 15: { 16: void localincrementbatch(counterincrement[] batch); 17: 18: counter[] read(string name); 19: 20: void replicatedupdates(counter[] updates); 21: } as you can see, this gives us very simple interface for the storage. we can either change the data locally (which modify our own storage) or we can get an update from a replica about its changes. there really isn’t much more to it, to be fair. the localincrementbatch() increment a local value, and read() will return all the values for a counter. there is a little bit of trickery involved in how exactly one would store the counter values. for now, i think we’ll store each counter as two step values. we’ll have a tree of multi tree values that will carry each value from each source. that means that a counter will take roughly 4kb or so. this is easy to work with and nicely fit the model voron uses internally. note that we’ll outline additional requirement for storage (searching for counter by prefix, iterating over counters, addresses of other servers, stats, etc) below. i’m not showing them here because they aren’t the major issue yet. over the wire skipping out on any optimizations that might be required, we will expose the following endpoints: get /counters/read?id=users/1/visits&users/1/posts <—will return json response with all the relevant values (already summed up). { “users/1/visits”: 43, “users/1/posts”: 3 } get /counters/read?id=users/1/visits&users/1/1/posts&raw=true <—will return json response with all the relevant values, per source. { “users/1/visits”: {“rvn1”: 21, “rvn2”: 22 } , “users/1/posts”: { “rvn1”: 2, “rvn3”: 1 } } post /counters/increment <– allows to increment counters. the request is a json array of the counter name and the change. for a real system, you’ll probably need a lot more stuff, metrics, stats, etc. but this is the high level design, so this would be enough. note that we are skipping the high performance stream based writes we outlined for time series. we’ll probably won’t need them, so that doesn’t matter, but they are an option if we need them. system behavior this is where it is really not interesting, there is very little behavior here, actually. we only have to read the data from the storage, sum it up, and send it to the user. hardly what i’ll call business logic. client api the client api will probably look something like this: 1: counters.increment("users/1/posts"); 2: counters.increment("users/1/visits", 4); 3: 4: using(var batch = counters.batch()) 5: { 6: batch.increment("users/1/posts"); 7: batch.increment("users/1/visits",5); 8: batch.submit(); 9: } note that we’re offering both batch and single api. we’ll likely also want to offer a fire & forget style, which will be able to offer even better performance (because they could do batching across more than a single thread), but that is out of scope for now. for simplicity sake, we are going to have the client just a container for all of endpoints that it knows about. the container would be responsible for… updating the client visible topology, selecting the best server to use at any given point, etc. user interface there isn’t much to it. just show a list of counter values in a list. allow to search by prefix, allow to dive into a particular counter and read its raw values, but that is about it. oh, and allow to delete a counter. deleting data honestly, i really hate deletes. they are very expensive to handle properly the moment you have more than a single node. in this case, there is an inherent race condition between a delete going out and another node getting an increment. and then there is the issue of what happens if you had a node down when you did the delete, etc. this just sucks. deletion are handled normally, (with the race condition caveat, obviously), and i’ll discuss how we replicate them in a bit. high availability / scale out by definition, we actually don’t want to have storage replication here. either log shipping or consensus based. we actually do want to have different values, because we are going to be modifying things independently on many servers. that means that we need to do replication at the database level. and that leads to some interesting questions. again, the hard part here is the deletes. actually, the really hard part is what we are going to do with the new server problem. the new server problem dictates how we are going to bring a new server into the cluster. if we could fix the size of the cluster, that would make things a lot easier. however, we are actually interested in being able to dynamically grow the cluster size. therefor, there are only two real ways to do it: add a new empty node to the cluster, and have it be filled from all the other servers. add a new node by backing up an existing node, and restoring as a new node. ravendb, for example, follows the first option. but it means that in needs to track a lot more information. the second option is actually a lot simpler, because we don’t need to care about keeping around old data. however, this means that the process of bringing up a new server would now be: update all nodes in the cluster with the new node address (node isn’t up yet, replication to it will fail and be queued). backup an existing node and restore at the new node. start the new node. the order of steps is quite important. and it would be easy to get it wrong. also, on large systems, backup & restore can take a long time. operationally speaking, i would much rather just be able to do something like, bring a new node into the cluster in “silent” mode. that is, it would get information from all the other nodes, and i can “flip the switch” and make it visible to clients at any point in time. that is how you do it with ravendb, and it is an incredibly powerful system, when used properly. that means that for all intents and purposes, we don’t do real deletes. what we’ll actually do is replace the counter value with delete marker. this turns deletes into a much simple “just another write”. it has the sad implication of not free disk space on deletes, but deletes tend to be rare, and it is usually fine to add a “purge” admin option that can be run on as needed basis. but that brings us to an interesting issue, how do we actually handle replication. the topology map to simplify things, we are going to go with one way replication from a node to another. that allows complex topologies like master-master, cluster-cluster, replication chain, etc. but in the end, this is all about a single node replication to another. the first question to ask is, are we going to replicate just our local changes, or are we going to have to replicate external changes as well? the problem with replicating external changes is that you may have the following topology: now, server a got a value and sent it to server b. server b then forwarded it to server c. however, at that point, we also have a the value from server a replicated directly to server c. which value is it supposed to pick? and what about a scenario where you have more complex topology? in general, because in this type of system, we can have any node accept writes, and we actually desire this to be the case , we don’t want this behavior. we want to only replicate local data, not all the data. of course, that leads to an annoying question, what happens if we have a 3 node cluster, and one node fails catastrophically. we can bring a new node in, and the other two nodes will be able to fill in their values via replication, but what about the node that is down? the data isn’t gone, it is still right there in the other two nodes, but we need a way to pull it out. therefor, i think that the best option would be to say that nodes only replicate their local state, except in the case of a new node. a new node will be told the address of an existing node in the cluster, at which point it will: register itself in all the nodes in the cluster (discoverable from the existing node). this assumes a standard two way replication link between all servers, if this isn’t the case, the operators would have the responsibility to setup the actual replication semantics on their own. new node now starts getting updates from all the nodes in the cluster. it keeps them in a log for now, not doing anything yet. ask that node for a complete update of all of its current state. when it has all the complete state of the existing node, it replays all of the remembered logs that it didn’t have a chance to apply yet. then it announces that it is in a valid state to start accepting client connections. note that this process is likely to be very sensitive to high data volumes. that is why you’ll usually want to select a backup node to read from, and that decision is an ops decision. you’ll also want to be able to report extensively on the current status of the node, since this can take a while, and ops will be watching this very closely. server name a node requires a unique name. we can use guids, but those aren’t readable, so we can use machine name + port, but those can change. ideally, we can require the user to set us up with a unique name. that is important for readability and for being able to alter see all the values we have in all the nodes. it is important that names are never repeated, so we’ll probably have a guid there anyway, just to be on the safe side. actual replication semantics since we have the new server problem down to an automated process, we can choose the drastically simpler model of just having an internal queue per each replication destination. whenever we make a change, we also make a note of that in the queue for that destination, then we start an async replication process to that server, sending all of our updates there. it is always safe to overwrite data using replication, because we are overwriting our own data, never anyone else. and… that is about it, actually. there are probably a lot of details that i am missing / would discover if we were to actually implement this. but i think that this is a pretty good idea about what this feature is about.
March 25, 2014
by Oren Eini
· 12,593 Views · 1 Like
article thumbnail
How to Use NodeManager to Control WebLogic Servers
In my previous post, you have seen how we can start a WebLogic admin and multiple managed servers. One downside with that instruction is that those processes will start in foreground and the STDOUT are printed on terminal. If you intended to run these severs as background services, you might want to try the WebLogic node manager wlscontrol.sh tool. I will show you how you can get Node Manager started here. The easiest way is still to create the domain directory with the admin server running temporary and then create all your servers through the /console application as described in last post. Once you have these created, then you may shut down all these processes and start it with Node Manager. 1. cd $WL_HOME/server/bin && startNodeManager.sh & 3. $WL_HOME/common/bin/wlscontrol.sh -d mydomain -r $HOME/domains/mydomain -c -f startWebLogic.sh -s myserver START 4. $WL_HOME/common/bin/wlscontrol.sh -d mydomain -r $HOME/domains/mydomain -c -f startManagedWebLogic.sh -s appserver1 START The first step above is to start and run your Node Manager. It is recommended you run this as full daemon service so even OS reboot can restart itself. But for this demo purpose, you can just run it and send to background. Using the Node Manager we can then start the admin in step 2, and then to start the managed server on step 3. The NodeManager can start not only just the WebLogic server for you, but it can also monitor them and automatically restart them if they were terminated for any reasons. If you want to shutdown the server manually, you may use this command using Node Manager as well: $WL_HOME/common/bin/wlscontrol.sh -d mydomain -s appserver1 KILL The Node Manager can also be used to start servers remotely through SSH on multiple machines. Using this tool effectively can help managing your servers across your network. You may read more details here: http://docs.oracle.com/cd/E23943_01/web.1111/e13740/toc.htm TIPS1: If there is problem when starting server, you may wnat to look into the log files. One log file is the/servers//logs/.out of the server you trying to start. Or you can look into the Node Manager log itself at $WL_HOME/common/nodemanager/nodemanager.log TIPS2: You add startup JVM arguments to each server starting with Node Manager. You need to create a file under /servers//data/nodemanager/startup.properties and add this key value pair:Arguments = -Dmyapp=/foo/bar TIPS3: If you want to explore Windows version of NodeManager, you may want to start NodeManager without native library to save yourself some trouble. Try adding NativeVersionEnabled=false to$WL_HOME/common/nodemanager/nodemanager.properties file.
March 24, 2014
by Zemian Deng
· 14,199 Views
article thumbnail
JavaScript Webapps with Gradle
Gradle, a versatile JVM build tool, effectively handles JavaScript and CSS tasks for web applications and server components.
March 24, 2014
by Kon Soulianidis
· 39,450 Views · 4 Likes
article thumbnail
Top 5 Reasons to Choose ScalaTest Over JUnit
Testing is a major part of our development process. After working with JUnit for some time we leaned back and thought: How can we improve our test productivity? Since we were all fond of Scala we looked at ScalaTest. We liked it from the start so we decided to go with ScalaTest for all new tests. Sure enough there were and are critics in the team who say “I just want to write my tests without having to bother with a new technology…” to convince even the last person on the team I will give you my top 5 reasons to choose ScalaTest over JUnit. 1. Multiple Comparisons Simple yet very nice is that you can do multiple comparisons for a single object. Say we have a list of books. Now we want to assure that the list contains exactly one book which is our book “Ruling the Universe”. The test code allows us to express it just like that: books should { not be empty and have size 1 and contain rulingTheUniverse } 2. Great DSLs There are many great DSLs to make the test code much shorter and nicer to read. These DSLs for Scala are much more powerful that those for Java. I will give you just two small examples for Mockito and Selenium. Mockito Sugar Say I have a book mock and I want to to check that the method publish has been called exactly once but I don’t care with which arguments. So here you go: val book = mock[Book] book expects 'publish withArgs (*) once Selenium We want to open our application in the browser check the title is “Aweseome Books” and then click on the link to explore books. With the Selenium DSL this is expressed like that: go to "http://localhost/book_app/index.html") pageTitle should be ("Awesome Books") click on linkText("Explore ...”) 3. Powerful Matchers Who needs assertions when you can have matchers? When I started out with ScalaTest I used a lot of assertions because thats what I knew. When I discovered matchers I started to use those as they are much more powerful and have a great syntax which allows you to write your test code very close to the what you actually want to express. I will give just a few examples to give you a first impression of just what you can do with matchers: Array(3,2,1) should have size 3// check the size of an array string should include regex "wo.ld"// check string against regular expression temp should be a 'file // check that temp is a file 4. Tag support JUnit has categories and ScalaTest has tags. You can tag your tests as you like and the execute only tests with certain tags or do other stuff with the tags. And that’s how you tag a test as “DbTest” and “SlowTest”: it must "save the book correctly"taggedAs(SlowTest, DbTest) in { // call to database } 5. JavaBean-style checking of object properties Say you have a book object with properties such as title and authors. Then you write a test where you want to verify the title is “Ruling the Universe” and it was published in 2012. In JUnit you write assertions like assertEquals(“Ruling the Universe”, book.getTitle()) and you need another assertion for the publication year. ScalaTest allows for JavaBean-style checking of object properties. So in ScalaTest you can declare the expected values for properties of an object. Instead of the assertions you write the property title of the book should be “Ruling the Universe” and the property publicationYear should be 2012. And thats how this looks in ScalaTest: book should have ( ‘title ("Ruling the Universe"), ‘author (List("Zaphod", "Ford")), ‘publicationYear (2012) ) Are you willing to give ScalaTest a try? You should. I like it more and more with every test I write and maybe you will too!
March 22, 2014
by Jan
· 14,077 Views · 1 Like
article thumbnail
Mock Final Class
Foreword If you already read some other blog post about unusual mocking, you can skip prelude via this link. I was asked to put together examples how to mock Java constructs well known for their testability issues: Mock private method Mock final method Mock final class Mock constructor Mock static method I am calling these techniques unusual mocking. I was worried that such examples without any guidance can be widely used by teammates not deeply experienced in mocking frameworks. Developers practicing TDD or BDD should be aware of testability problems behind these constructs and try to avoid them when designing their tests and modules. That is the reason why you probably wouldn't be facing such unusual mocking often on projects using these great programming methodologies. But sometimes you have to extend or maintain legacy codebase that usually contains low cohesive classes. In most cases there isn't time in current hectic agile world to make such class easy to unit test standard way. When you are trying to unit test such class you often realize that unusual mocking is needed. That is why I decided to create and share refactoring considerations alongside with examples and workarounds for unusual mocking. Examples are using Mockito and PowerMock mocking frameworks and TestNG unit testing framework. Mock final class Refactoring considerations Change class to non-final (remove final keyword) and test it standard way. This is technique I use always when I can change code of final class. Usage of PowerMock Before usage of this example, please carefully consider if it is worth to bring bytecode manipulation risks into your project. They are gathered in this blog post. In my opinion it should be used only in very rare and non-avoidable cases. Test shows how to mock final class by PowerMock framework. Example covers: Mocking of method with return value in final class Mocking of final void method in final class Verifying of method calls in final class Final class: public final class Plane { public static final int ENGINE_ID_RIGHT = 2; public static final int ENGINE_ID_LEFT = 1; public boolean verifyAllSystems() { throw new UnsupportedOperationException("Fail if not mocked!"); } public void startEngine(int engineId) { throw new UnsupportedOperationException( "Fail if not mocked! [engineId=" + engineId + "]"); } } Class under test: public class Pilot { private Plane plane; public Pilot(Plane plane) { this.plane = plane; } public boolean readyForFlight() { plane.startEngine(Plane.ENGINE_ID_LEFT); plane.startEngine(Plane.ENGINE_ID_RIGHT); return plane.verifyAllSystems(); } } Test: @PrepareForTest(Plane.class) public class PilotTest extends PowerMockTestCase { @Test public void testReadyForFlight() { Plane planeMock = PowerMockito.mock(Plane.class); Pilot pilot = new Pilot(planeMock); Mockito.when(planeMock.verifyAllSystems()).thenReturn(true); // testing method boolean actualStatus = pilot.readyForFlight(); Assert.assertEquals(actualStatus, true); Mockito.verify(planeMock).startEngine(Plane.ENGINE_ID_LEFT); Mockito.verify(planeMock).startEngine(Plane.ENGINE_ID_RIGHT); } } Links Source code can be downloaded from Github. Other unusual mocking examples: Mock private method Mock final method Mock constructor Mock static method
March 17, 2014
by Lubos Krnac
· 55,013 Views
article thumbnail
Creating Complex Test Configurations with Red Deer
This is the second in a series of posts on the new “Red Deer” (https://github.com/jboss-reddeer/reddeer) open source testing framework for Eclipse. In the previous post in this series, we introduced Red Deer, learned how to install it into Eclipse, examined some of its cool features, and built and ran a sample test program from scratch. One of the challenges in creating effective automated tests is in making the tests self-sufficient enough to be able to set up their required operation environment, and robust enough to be able to determine whether that operating environment has been set up correctly. In the first post in this series, we took a quick look at Red Deer’s implementation of Requirements classes. In this post, we’ll take a more detailed look at Requirements, including how Red Deer supports your creating custom Requirements. The Case for Automated Test Requirements Let’s start by setting the context for why test programs need requirements. It’s often the case that a set of automated tests runs unattended and all the tests fail, not due to a bug in the software under test, but due to a broken or incomplete test environment. When we refer to a Red Deer “requirement,” we’re talking about actions that must be performed, or objects that must be created, before a test can be run. Examples of these requirements are having a user account defined or a connection to a database created and verified. What makes using Red Deer requirements different from your creating a less formal set of requirements with the @BeforeClass annotation provided by JUnit, is that if requirements are not met, then the test in question is not run. This can save you a lot of test execution time and test failure debugging time. Red Deer requirements are implemented in the RedDeerSuite. A test that makes use of requirements is must be run with a RedDeerSuite suite and annotated with @RunWith(RedDeerSuite.class) OOTB Red Deer Requirements As we saw in the first post in this series, Red Deer currently provides OOTB (out of the box) predefined requirements that enable you to clean out your current workspace and open a perspective. Using these requirements is simple. All you have to do is to add these import statements to your Red Deer test programs: import org.jboss.reddeer.eclipse.ui.perspectives.JavaBrowsingPerspective; import org.jboss.reddeer.requirements.cleanworkspace.CleanWorkspaceRequirement.CleanWorkspace; import org.jboss.reddeer.requirements.openperspective.OpenPerspectiveRequirement.OpenPerspective; And, we also have to add a reference to org.jboss.reddeer.requirements to the required bundle list in our example’s MANIFEST.MF file. And finally, add these annotations to the test program: @CleanWorkspace @OpenPerspective(JavaBrowsingPerspective.class) What if you want to define your own custom requirements? Let’s move on and examone how Red Deer supports that too. Different Ways to Implement New Red Deer Requirements Red Deer supports (4) ways to implement new requirements. We’ll look at them in order of their relative complexity: Simple Requirements Requirements with Parameters Requirements with Property Based Configuration Requirements with a Custom Schema In order to examine how Red Deer supports implementing new requirements, we’ll actually create some new requirements in Red Deer source code. In order to do this, we’ll have to download a copy of Red Deer’s source code. To perform this download, navigate to your desired directory and enter this command: git clone https://github.com/jboss-reddeer/reddeer.git And then, import Red Deer into eclipse as a set of existing Maven projects: If you navigate to the top level of the directory into which you downloaded the Red Deer source code, you’ll see this: What you want to do is to select all of the Red Deer projects. After you press the “Next>” key, Eclipse will import all the Red Deer packages as maven projects. (This may take a few minutes.) OK, now we can move on to creating some new requirements. We’ll start with the simplest of the (4) types, a simple requirement. Implementing a Simple Requirement A simple requirement consists of (2) parts: a “fulfilling” class that provides the code executed when the requirement is invoked, and an annotation that references that fulfilling class. As an illustration, let’s look at the skeleton “AdminUserRequirement” provided with your Red Deer download. This requirement is intended to serve as an example for implementing a full requirement to ensure that an admin-level user is defined before an attempt is made to run a test. The source file you want to look for is: /plugins/org.jboss.reddeer.examples/src/org/jboss/reddeer/junit/annotation/simple/AdminUserRequirement.java While it’s a small file, it’s a full example. It’s worthwhile examining it line-by-line: package org.jboss.reddeer.junit.annotation.simple; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.jboss.reddeer.junit.requirement.Requirement; import org.jboss.reddeer.junit.annotation.simple.AdminUserRequirement.AdminUser; /** * Admin user test requirement * @author lucia jelinkova * */ public class AdminUserRequirement implements Requirement { @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface AdminUser { } public boolean canFulfill() { // return true if you can connect to the database return true; } public void fulfill() { // create an admin user in the database if it does not exist yet } public void setDeclaration(AdminUser declaration) { // no need to access the annotation } } The important elements in this file are: Line 17 - @Retention - Specifies how the marked annotation is stored—Whether in code only, compiled into the class, or available at runtime through reflection. Line 18 - @Target - Marks another annotation to restrict the types of Java elements to which the the annotation can be applied Line 20 - AdminUser interface - This defines the object type used by the defined requirement. Line 23 - canFulfill method - In a fully written requirement this method will include the code to determine if the requirement can be met (or “fulfilled”). This method is set to always return a value of true. Line 32 - fulfill method - And here is the code that will be executed if the canFulfill method returns a value of true. For an example of the corresponding annotation in action, let’s look at the test program that is included with the fulfilling class. The test program is here: /plugins/org.jboss.reddeer.examples/src/org/jboss/reddeer/junit/annotation/simple/AdminUserTest.java This test program is also very short as it is a skeleton. The outline is there, but the specific logic that to implement the AdminUser requirement is left as an “exercise for the reader.” package org.jboss.reddeer.junit.annotation.simple; import org.jboss.reddeer.junit.runner.RedDeerSuite; import org.jboss.reddeer.junit.annotation.simple.AdminUserRequirement.AdminUser; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(RedDeerSuite.class) @AdminUser /** * Test with AdminUser requirement * @author lucia jelinova * */ public class AdminUserTest { @Test public void test(){ // put test logic here } } The @AdminUser annotation on line NN tells the whole story. When this annotation is executed, the fulfilling class is invoked and if the “canFulfill()” method returns true, the test is executed. If the method returns false, then the test is not executed. Let’s run this test and see what happens. First, locate the AdminUserTest.java file in the eclipse Navigator view: Then, right-click and specify that it be executed as a JUnit test: And, not surprisingly, here’s the successful output from the test: Before we move on, let’s modify the canFulFill() method to return a false value, and rerun the test. The results look like this: 22:11:04.923 INFO [main][RequirementsRunnerBuilder] Found test class org.jboss.reddeer.junit.annotation.simple.AdminUserTest 22:11:04.924 INFO [main][RequirementsBuilder] Creating requirements for test class org.jboss.reddeer.junit.annotation.simple.AdminUserTest 22:11:04.925 DEBUG [main][RequirementsBuilder] Found requirement class org.jboss.reddeer.junit.annotation.simple.AdminUserRequirement for annotation interface org.jboss.reddeer.junit.annotation.simple.AdminUserRequirement$AdminUser 22:11:04.927 INFO [main][Requirements] Requirement class org.jboss.reddeer.junit.annotation.simple.AdminUserRequirement can be fulfilled: false 22:11:04.927 INFO [main][RequirementsRunnerBuilder] All requirements cannot be fulfilled, the test will NOT run So, this time, the requirement was not met and the test was not run. Note that the requirement did the work for us. We did not have to write a lot of new code to determine if the requirement had been met to decide whether or not to run the test. That’s all well and good for a simple requirement. But what about if we want to make the requirement a bit more flexible by enabling us to pass it a parameter? Let’s look at that next. Implementing a Requirement with Parameters In order to implement a requirement that accepts one or more parameters, we have to make two additions to the simple requirement that we just examined. First, we have to use a different requirement definition. The code that we want to look at this time is here: /plugins/org.jboss.reddeer.examples/src/org/jboss/reddeer/junit/annotation/advanced/UserRequirement.java The file looks like this: package org.jboss.reddeer.junit.annotation.advanced; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.jboss.reddeer.junit.requirement.Requirement; import org.jboss.reddeer.junit.annotation.advanced.UserRequirement.User; /** * Parameterized requirement with parameter name * @author vpakan * */ public class UserRequirement implements Requirement { @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface User { String name(); } private User user; public boolean canFulfill() { // return true if you can connect to the database return true; } public void fulfill() { System.out.println("Fulfilling reuirement User with name: " + user.name()); // create an admin user in the database if it does not exist yet } public void setDeclaration(User user) { this.user = user; } } The important difference between this class and the original AdminUserRequirement that we examined a moment ago is: Line 20 - The interface “User” now defines a String parameter “name” and on line NNN here the User object is defined. Second, we have to change the declaration of the requirement in the test program. The test program that we’ll look at this time is here: /plugins/org.jboss.reddeer.examples/src/org/jboss/reddeer/junit/annotation/advanced/UserTest.java Finally, our test program for this requirement looks like this: package org.jboss.reddeer.junit.annotation.advanced; import org.jboss.reddeer.junit.runner.RedDeerSuite; import org.jboss.reddeer.junit.annotation.advanced.UserRequirement.User; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(RedDeerSuite.class) @User(name="admin") /** * Test with parameterized requirement User * @author lucia jelinkova * */ public class UserTest { @Test public void test(){ // put test logic here } } The interesting line in this test is: Line 8 - @User(name="admin") - Where we set the value of the “name” parameter. When we run the UserTest as a JUnit test, we see this output: 20:46:03.554 INFO [main][RequirementsRunnerBuilder] Found test class org.jboss.reddeer.junit.annotation.advanced.UserTest 20:46:03.555 INFO [main][RequirementsBuilder] Creating requirements for test class org.jboss.reddeer.junit.annotation.advanced.UserTest 20:46:03.556 DEBUG [main][RequirementsBuilder] Found requirement class org.jboss.reddeer.junit.annotation.advanced.UserRequirement for annotation interface org.jboss.reddeer.junit.annotation.advanced.UserRequirement$User 20:46:03.558 INFO [main][Requirements] Requirement class org.jboss.reddeer.junit.annotation.advanced.UserRequirement can be fulfilled: true 20:46:03.558 INFO [main][RequirementsRunnerBuilder] All requirements can be fulfilled, the test will run 20:46:03.575 INFO [main][RedDeerSuite] RedDeer suite created 20:46:03.584 INFO [main][Requirements] Fulfilling requirement of class org.jboss.reddeer.junit.annotation.advanced.UserRequirement Fulfilling requirement User with name: admin 20:46:03.585 DEBUG [main][RequirementsRunner] Injecting fulfilled requirements into test instance 20:46:03.587 INFO [main][RequirementsRunner] Started test: test(org.jboss.reddeer.junit.annotation.advanced.UserTest)20:46:03.588 INFO [main][RequirementsRunner] Finished test: test(org.jboss.reddeer.junit.annotation.advanced.UserTest) While it makes requirements more flexible when you are able to add parameters to their definition, it is still limited as a solution as you have to handle the individual parameters one by one. Fortunately, Red Deer also supports defining test configurations in your own custom XML schemas. Defining Complex Configurations - Two Approaches Red Deer supports two different approaches to defining complex configurations. You can either: Define the configuration as a set of (key=value) properties. If you choose this approach, you will have to also define setter methods for each property in your requirement’s fulfilling class. Create a custom XML schema. If you choose this approach, you will have to create a configuration object in your test code and then inject that object into your requirement. Regardless of which approach you choose, you store the configuration data in either a single XML file, or directory of XML files and then pass those files to your test program by defining this JVM argument when you run your test programs: -Dreddeer.config=/home/path/to/file/or/directory Let’s examine each of these approaches in detail. We’ll start with the properties based approach. Requirements with a Property Based Configuration The first thing we have to do to use a property based configuration is to define the properties. We’ll do this in an an XML file that complies with the Red Deer requirements XSD schema file. You can view the XSD here: http://cloud.github.com/downloads/jboss-reddeer/reddeer/RedDeerSchema.xsd The code for this example is here: /jboss/local/reddeer_fork/reddeer/plugins/org.jboss.reddeer.examples/src/org/jboss/reddeer/junit/configuration/simple And - here’s our properties file. Note that the requirement defined in this file contains two properties: name and ip (IP address). Let’s now expand on the “UserRequirement” example that we defined a few minutes ago. What we want to be able to do is to remove hardcoded requirements data from the source code and instead define that data in set of properties. To use this requirements.xml file, we have to make some changes to the UserRequirement.java class. package org.jboss.reddeer.junit.annotation.simple; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.jboss.reddeer.junit.requirement.Requirement; import org.jboss.reddeer.junit.annotation.simple.UserRequirement.User; import org.jboss.reddeer.junit.requirement.PropertyConfiguration; /** * Admin user test requirement * @author lucia jelinkova */ public class UserRequirement implements Requirement , PropertyConfiguration { @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface User { } private String name; private String ip; public boolean canFulfill() { // return true if you can connect to the database return true; } public void fulfill() { System.out.println("Fulfilling User requirement with\nName: " + name + "\nIP: " + ip); // create an admin user in the database if it does not exist yet } @Override public void setDeclaration(User user) { // annotation has no parameters no need to store reference to it } public void setName(String name) { this.name = name; } public void setIp(String ip) { this.ip = ip; } public String getName() { return name; } public String getIp() { return ip; } } The important changes are the addition of this import statement at line 8: import org.jboss.reddeer.junit.requirement.PropertyConfiguration And the addition of the implement clauses for the Requirement (with a type of User), and the PropertyConfiguration (so that the properties can be read) at line 15: public class UserRequirement implements Requirement , PropertyConfiguration And addition of the setter methods for the name and ip properties. Finally, here is the updated test program: package org.jboss.reddeer.junit.annotation.simple; import org.jboss.reddeer.junit.runner.RedDeerSuite; import org.jboss.reddeer.junit.annotation.simple.UserRequirement.User; import org.junit.Test; import org.junit.runner.RunWith; import org.jboss.reddeer.junit.requirement.inject.InjectRequirement; @RunWith(RedDeerSuite.class) @User /** * Test with AdminUser requirement * @author lucia jelinova * */ public class UserTest { @InjectRequirement private UserRequirement userRequirement; @Test public void test(){ System.out.println("The test is running"); System.out.println(userRequirement.getName()); // put test logic here } } What’s new in the test program is the addition of the import statement for the requirement injection: import org.jboss.reddeer.junit.requirement.inject.InjectRequirement; And the code to define and inject the UserRequirement: @InjectRequirement private UserRequirement userRequirement; When we run the test, we have to reference the configuration file via a Java VM argument . This means that we must define a new “run configuration” that is based on the JUnit run configuration provided in Eclipse and provide the VM argument that references the configuration file: In our example, the -Dreddeer.config VM argument is defined as: -Dreddeer.config=/jboss/local/reddeer_fork/reddeer/plugins/org.jboss.reddeer.examples/src/org/jboss/reddeer/junit/annotation/simple/reddeer.xml To execute the test, right-click on the UserTest class, and select the run configuration we just created: And, the test generates this test output in the console: 22:40:50.988 INFO [main][RedDeerSuite] Creating RedDeer suite... 22:40:50.990 INFO [main][SuiteConfiguration] Looking up configuration files defined via property reddeer.config=/jboss/local/reddeer_fork/reddeer/plugins/org.jboss.reddeer.examples/src/org/jboss/reddeer/junit/annotation/simple/reddeer.xml 22:40:50.991 INFO [main][SuiteConfiguration] Found configuration file /jboss/local/reddeer_fork/reddeer/plugins/org.jboss.reddeer.examples/src/org/jboss/reddeer/junit/annotation/simple/reddeer.xml 22:40:50.992 INFO [main][RedDeerSuite] Adding suite with name reddeer.xml to RedDeer suite 22:40:51.012 INFO [main][RequirementsRunnerBuilder] Found test class org.jboss.reddeer.junit.annotation.simple.UserTest 22:40:51.025 INFO [main][RequirementsBuilder] Creating requirements for test class org.jboss.reddeer.junit.annotation.simple.UserTest 22:40:51.027 DEBUG [main][RequirementsBuilder] Found requirement class org.jboss.reddeer.junit.annotation.simple.UserRequirement for annotation interface org.jboss.reddeer.junit.annotation.simple.UserRequirement$User 22:40:51.027 DEBUG [main][PropertyBasedConfigurator] Setting property based configuration to requirement class org.jboss.reddeer.junit.annotation.simple.UserRequirement 22:40:51.031 DEBUG [main][XMLReader] Reading configuration for class org.jboss.reddeer.junit.internal.configuration.entity.PropertyBasedConfiguration 22:40:51.827 DEBUG [main][PropertyBasedConfigurator] Configuration successfully set 22:40:51.828 INFO [main][Requirements] Requirement class org.jboss.reddeer.junit.annotation.simple.UserRequirement can be fulfilled: true 22:40:51.828 INFO [main][RequirementsRunnerBuilder] All requirements can be fulfilled, the test will run 22:40:51.865 INFO [main][RedDeerSuite] RedDeer suite created 22:40:51.874 INFO [main][Requirements] Fulfilling requirement of class org.jboss.reddeer.junit.annotation.simple.UserRequirement Fulfilling User requirement with Name: USERS_ADMINISTRATION IP: 127.0.0.1 22:40:51.875 DEBUG [main][RequirementsRunner] Injecting fulfilled requirements into test instance 22:40:51.876 INFO [main][RequirementsRunner] Started test: test reddeer.xml(org.jboss.reddeer.junit.annotation.simple.UserTest) 22:40:51.876 INFO [main][RequirementsRunner] Started test: test reddeer.xml(org.jboss.reddeer.junit.annotation.simple.UserTest) The test is running USERS_ADMINISTRATION 22:40:51.878 INFO [main][RequirementsRunner] Finished test: test reddeer.xml(org.jboss.reddeer.junit.annotation.simple.UserTest) 22:40:51.878 INFO [main][RequirementsRunner] Finished test: test reddeer.xml(org.jboss.reddeer.junit.annotation.simple.UserTest) Requirements with a Custom Schema The fourth and final approach to defining new requirements is to create a custom XML schema. This is the most complex approach, but it also provides you with the most flexibility as you can more easily share requirements in multiple configuration files. Also, this approach can protect you against forgetting to define properties in the configuration files by designating specific properties as required XML elements. To use this approach, you create a custom XML schema, then you create a configuration object in the test programs, and inject that object into your requirement. The configuration details are defined in an XML file and accessed through JAXB annotations. Let’s take a look at an example. The code for this example is available in Red Deer here: /plugins/org.jboss.reddeer.examples/src/org/jboss/reddeer/junit/configuration/advanced In order to use a custom XML schema, you need a custom schema. In this example, the schema is defined in a local file: /plugins/org.jboss.reddeer.examples/src/org/jboss/reddeer/junit/configuration/advanced/RedDeerRequirements.xsd This example schema is fairly simple, but it provides the flexibility needed for the example to define a test configuration of key=value pairs in the context of testruns and requirements. Also, the schema enforces the “required” setting for the requirement name. The configuration for requirement is defined in an XML requirement configuration file, the format of which complies with the custom schema: USERS_ADMINISTRATION 127.0.0.1 1111 In order to make use of this configuration, the Requirement class must instantiate a “UserConfiguration” object for the requirement. The UserRequirement class implements the org.jboss.reddeer.junit.requirement.CustomConfiguration interface with and specifies a type of UserConfiguration to enable the use of custom configurations: package org.jboss.reddeer.junit.configuration.advanced; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.jboss.reddeer.junit.requirement.CustomConfiguration; import org.jboss.reddeer.junit.requirement.Requirement; import org.jboss.reddeer.junit.configuration.advanced.UserRequirement.User; /** * User requirement using configuration from custom xml file * @author lucia jelinkova * */ public class UserRequirement implements Requirement, CustomConfiguration { @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface User { String name(); } private User user; private UserConfiguration userConfiguration; public boolean canFulfill() { // return true if you can connect to the database return true; } public void fulfill() { System.out.println("fulfiling requirement User with\nName: " + user.name() + "\nDB name: " + userConfiguration.getDbName() + "\nPort: " + userConfiguration.getPort() + "\nIP: " + userConfiguration.getIp()); // create an admin user in the database if it does not exist yet } public void setDeclaration(User user) { this.user = user; } public Class getConfigurationClass() { return UserConfiguration.class; } public void setConfiguration(UserConfiguration config) { this.userConfiguration = config; } } The UserConfiguration object (see line 25) is used by the org.jboss.reddeer.junit.requirement.CustomConfiguration class to provide the values for the requirement. The UserConfiguration definition (see below) maps the requirement as defined in the elements defined in the requirement XML file. package org.jboss.reddeer.junit.configuration.advanced; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; /** * Stores user requirement configuration loaded from custom xml file * @author lucia jelinkova * */ @XmlRootElement(name="user-requirement", namespace="http://www.jboss.org/NS/user-schema") public class UserConfiguration { private String dbName; private String ip; private String port; public String getIp() { return ip; } @XmlElement(namespace="http://www.jboss.org/NS/user-schema") public void setIp(String ip) { this.ip = ip; } public String getPort() { return port; } @XmlElement(namespace="http://www.jboss.org/NS/user-schema") public void setPort(String port) { this.port = port; } public String getDbName() { return dbName; } @XmlElement(name="db-name", namespace="http://www.jboss.org/NS/user-schema") public void setDbName(String dbName) { this.dbName = dbName; } } Note the getter and setter methods in the class definition. These methods make use of JAXB annotations to access the configuration element values. The test program looks largely the same as the test programs that we’ve used in the earlier examples. (It’s a nice characteristic of Red Deer tests in that since the “heavy lifting” is performed by the Red Deer harness, the tests can be kept simple, and therefore kept easy to maintain.) package org.jboss.reddeer.junit.configuration.advanced; import org.jboss.reddeer.junit.runner.RedDeerSuite; import org.jboss.reddeer.junit.configuration.advanced.UserRequirement.User; import org.junit.Test; import org.junit.runner.RunWith; /** * User test using configuration from custom xml file * Set VM parameter -Dreddeer.config to point to directory with requirements.xml file * -Dreddeer.config=${project_loc}/src/org/jboss/reddeer/junit/configuration/advanced * @author lucia jelinkova */ @RunWith(RedDeerSuite.class) @User(name="admin") public class UserTest { @Test public void test(){ // put your test logic here } } When the program is run, the console shows that the requirement was successfully met: 21:26:25.075 INFO [main][RedDeerSuite] Creating RedDeer suite... 21:26:25.077 INFO [main][SuiteConfiguration] Looking up configuration files defined via property reddeer.config=/jboss/local/reddeer_fork/reddeer/plugins/org.jboss.reddeer.examples/src/org/jboss/reddeer/junit/configuration/advanced/requirements.xml 21:26:25.077 INFO [main][SuiteConfiguration] Found configuration file /jboss/local/reddeer_fork/reddeer/plugins/org.jboss.reddeer.examples/src/org/jboss/reddeer/junit/configuration/advanced/requirements.xml 21:26:25.078 INFO [main][RedDeerSuite] Adding suite with name requirements.xml to RedDeer suite 21:26:25.084 INFO [main][RequirementsRunnerBuilder] Found test class org.jboss.reddeer.junit.configuration.advanced.UserTest 21:26:25.087 INFO [main][RequirementsBuilder] Creating requirements for test class org.jboss.reddeer.junit.configuration.advanced.UserTest 21:26:25.089 DEBUG [main][RequirementsBuilder] Found requirement class org.jboss.reddeer.junit.configuration.advanced.UserRequirement for annotation interface org.jboss.reddeer.junit.configuration.advanced.UserRequirement$User 21:26:25.089 DEBUG [main][CustomConfigurator] Setting custom configuration to requirement class org.jboss.reddeer.junit.configuration.advanced.UserRequirement 21:26:25.090 DEBUG [main][CustomConfigurator] Configuration object associated with requirement class org.jboss.reddeer.junit.configuration.advanced.UserRequirement is class org.jboss.reddeer.junit.configuration.advanced.UserConfiguration 21:26:25.090 DEBUG [main][XMLReader] Reading configuration for class org.jboss.reddeer.junit.configuration.advanced.UserConfiguration 21:26:25.782 DEBUG [main][CustomConfigurator] Configuration successfully set 21:26:25.832 INFO [main][Requirements] Requirement class org.jboss.reddeer.junit.configuration.advanced.UserRequirement can be fulfilled: true 21:26:25.832 INFO [main][RequirementsRunnerBuilder] All requirements can be fulfilled, the test will run 21:26:25.911 INFO [main][RedDeerSuite] RedDeer suite created 21:26:25.921 INFO [main][Requirements] Fulfilling requirement of class org.jboss.reddeer.junit.configuration.advanced.UserRequirement fulfiling requirement User with Name: admin DB name: USERS_ADMINISTRATION Port: 1111 IP: 127.0.0.1 21:26:25.922 DEBUG [main][RequirementsRunner] Injecting fulfilled requirements into test instance 21:26:25.923 INFO [main][RequirementsRunner] Started test: test requirements.xml(org.jboss.reddeer.junit.configuration.advanced.UserTest) 21:26:25.924 INFO [main][RequirementsRunner] Started test: test requirements.xml(org.jboss.reddeer.junit.configuration.advanced.UserTest) 21:26:25.925 INFO [main][RequirementsRunner] Finished test: test requirements.xml(org.jboss.reddeer.junit.configuration.advanced.UserTest) 21:26:25.925 INFO [main][RequirementsRunner] Finished test: test requirements.xml(org.jboss.reddeer.junit.configuration.advanced.UserTest) Before we move on, let’s try introducing an error in the XML test configuration and then see how Red Deer can trap that error. I don’t know about you, but avoiding typos is sometimes difficult for me. Let’s “inadvertently” remove the (required) name for the requirement. And rerun the test. This time, the console output shows: ERROR [main][XMLReader] cvc-complex-type.4: Attribute 'name' must appear on element 'user:user-requirement'. And the Junit output shows: org.jboss.reddeer.junit.configuration.RedDeerConfigurationException: Xml configuration is not valid. Recap In this post, we examined the (4) ways in which Red Deer supports creating your own custom test configurations. These methods range from simple requirements that optionally include parameters, to more complex requirements that can be defined in external XML files, either as key=value pairs or in a custom schema, that can be be shared between multiple test cases. It’s often the case that automated test runs can fail not because of bugs in software under test, but because the environment required by the test was properly initialized. Red Deer, by providing multiple approaches to create custom requirements helps you to ensure that your test failures can be more easily debugged and configuration errors are detected. What’s Next? In the next post in this series, we’ll take a look at how Red Deer makes creating new tests from scratch easier through its keystroke recorder feature. References https://github.com/jboss-reddeer/reddeer/wiki/Requirements http://www.oracle.com/technetwork/articles/javase/index-140168.html (JAXB)
March 14, 2014
by Len DiMaggio
· 6,857 Views
article thumbnail
Automating the build of MSI setup packages on Jenkins
a short "how-to" based on an issue one of my work mates recently faced when trying to automate the creation of an msi package on jenkins. normally, visual studio solutions can be build on jenkins by using the appropriate msbuild plugin . apparently though, for visual studio setup projects, msbuild cannot be used and one has to switch to using visual studio itself to execute the build. so the first approach was to use devenv.exe as follows devenv.exe visualstudiosolution.sln /build "release" while this works, the problem is that it is an "async call", meaning that the compilation goes on in the background while the console from which the build is executed, immediately returns. obviously this isn't suited for being used on jenkins. searching around for a while, it turned out that you have to use devenv.com instead of devenv.exe : "c:\program files (x86)\microsoft visual studio 10.0\common7\ide\devenv.com"visualstudiosolution.sln /build "release" once you got that, integrating everything into jenkins is quite straightforward: (obviously you may also simply set an environment variable pointing to devenv.com on your build server rather than indicating the entire path)
March 13, 2014
by Juri Strumpflohner
· 13,587 Views
article thumbnail
A Template for Formulating Great Sprint Goals
I find it helpful to consider three questions when choosing a sprint goal: Why do we carry out the sprint? How do we reach its goal? And how do we know that the goal has been met? My sprint goal template therefore consists of three main parts: the actual goal, the method employed to reach the goal, and the metrics to determine if the goal has been met. It additionally provides a header section that allows you to state to which product and sprint the goal belongs, as the picture below shows. You can download the template as a PDF from romanpichler.com/tools/sprint-goal-template/ or by clicking on the image below. The template above has grown out of my experience of working with Scrum for more than ten years, and it is inspired by the scientific method and Lean Startup. Let’s have a look at the template sections in more detail. The Goal Section The goal section states why it is worthwhile to undertake the sprint. Examples are: Test an assumption about the user interaction and learn what works best for the user, for instance: “Will users be willing to register before using the product features?” Address a technical risk such as: “Does the architecture enable the desired performance?” Release a feature, for instance: “Get the reporting feature for general release.” The sprint goal hence differs from listing the user stories that should be implemented. It communicates the reason for carrying out the work, and it provides a motivation for running the sprint. The sprint goal should be shared: The product owner and the development team should believe that working towards the goal is the right thing to do. To choose the right sprint goal I find it helpful to consider the amount of uncertainty present. In the early sprints, addressing risks and testing assumptions allows me to learn about what the product should look like and do and how it is built. Once the key risks and critical assumptions have been dealt with, I like to focus on completing and optimising features, as the following picture shows: The Method Section This section addresses the question of how the goal is met. The default Scrum answer is simple: Create a (potentially shippable) product increment using the high-priority product backlog items, and demo it to the stakeholders in the sprint review meeting. But writing software and employing a product demo are not always the best methods to achieve the goal! A paper prototype can be good enough to test a visual design idea or an assumption about the user interaction, for instance. What’s more, other methods such as carrying out a usability test or releasing software to run an A/B test may well be more effective than a product demo. You should therefore carefully choose the right method and state it in this section. But don’t stop there. Determine the test group, the people who should provide feedback and data. Who these individuals are depends on the sprint goal: If you are validating an assumption about the visual design, the user interaction or the product functionality, then you probably want to collect feedback and data from the users. But if you are addressing a technical risk, then users may not be able to help you. Consider inviting a senior developer or architect from another team instead. Stating the test group clarifies who “the stakeholders” are, who is required to provide feedback so that the right product is developed. The Metrics Section The metrics section communicates how you determine if the goal has been met. Which metrics you use depends on the method chosen. For a product demo, you may state that at least two thirds of the stakeholders present should respond positively to the new feature, for instance; for a usability test, at least three of the five testers are complete the task successfully in less than a minute; and for the release of a new feature, you might say that at least 80% of the users use the new functionality at least once within five days after launching the feature. Whichever metrics you choose, make sure that they allow you to understand if and to which extent you have met the goal. The Header Section The header section consists of the two subsections “Product” and “Sprint”. They simply allow you to state which product and which sprint the goal belongs to. Customise this section according to your needs. If you work for an agencies or an IT solution provider, you could replace “Product” with “Project”, for instance. User Stories and the Sprint Goal You may be wondering how the template relates to the user stories. Let me first reiterate that your sprint goal should differ from your user stories. The goal explains the why it is a good idea to carry out the sprint an implement the stories. The user stories enable you to reach the goal. It’s a common mistake to confuse the two. To connect the template and the stories you have two options: You can state the relevant user stories in the template’s method section, or you can list them separately on the sprint backlog, as the following picture illustrates. In the picture above, the sprint goal is stated on the left to the sprint backlog, which lists the user stories and the tasks required to meet the goal in form of a task board. Learn more You can learn more about choosing effective sprint gaols and applying the sprint goal template by attending my Certified Scrum Product Owner training course. I have written in more detail about sprint planning in my book “Agile Product Management with Scrum”. Please contact me for onsite and virtual product owner training.
March 12, 2014
by Roman Pichler
· 14,147 Views · 1 Like
article thumbnail
Mock Constructor
Foreword If you already read some other blog post about unusual mocking, you can skip prelude via this link. I was asked to put together examples of how to mock Java constructs well know for their testability issues: Mock private method Mock final method Mock final class Mock constructor Mock static method I am calling these techniques unusual mocking. I was worried that such examples without any guidance can be widely used by teammates not deeply experienced in mocking frameworks. Developers practicing TDD or BDD should be aware of testability problems behind these constructs and try to avoid them when designing their tests and modules. That is the reason why you probably wouldn't be facing such unusual mocking often on project using these great programming methodologies. But sometimes you have to extend or maintain legacy codebase that usually contains low cohesive classes. In most cases there isn't time in current hectic agile world to make such class easy to unit test standard way. When you are trying to unit test such class you often realize that unusual mocking is needed. That is why I decided to create and share refactoring considerations alongside with examples and workarounds for unusual mocking. Examples are using Mockito and PowerMock mocking frameworks and TestNG unit testing framework. Mock constructor Refactoring considerations If your testing method creates instance/s of some type, there are two possibilities what can happen with these instances Created instance/s are returned from testing method. They are in this case part of the testing method API. This can be tested by verifying against created instances rather than constructor method call. If target instances doesn't have hashCode/equals contract implemented, you can still create test specific comparator to verify created data. Created instances are used as parameter/s passed to some dependency object. This dependency object of testing class is most probably mocked. In this case it's better idea to capture arguments of dependency method call and verify them. Mockito offers good support for this. Created instances are temporary objects that support testing method job. In this case you shouldn't care about creation of these instances, because you should treat testing module as black box that doing the job, but you don't know how. Create factory class for constructing instances and mock it standard way. If that fits to requirement -> Abstract factory design pattern Workaround using Mockito This is my preferred technique when I need to mock constructor. I believe that minor exposing of internal implementation in flavor to enhance testability of testing module is much lower risk for project than fall into bytecode manipulation mocking framework like PowerMock or JMockIt. This technique involves: Encapsulating the constructor into method with default access modifier Partial mock (spy) is used to mock this method during testing Mockito example covers: Partial mocking of factory method Verifying of mocked factory method call Class under test: public class CarFactoryMockito { Car carFactoryMethod(String type, String color) { return new Car(type, color); } public Car constructCar(String type, String color) { carFactoryMethod(type, color); // ... other logic needed to be tested ... return carFactoryMethod(type, color); } } Test: public class CarFactoryMockitoTest { private static final String TESTING_TYPE = "Tatra"; private static final String TESTING_COLOR = "Black"; @Test public void testConstructCar() { CarFactoryMockito carFactory = new CarFactoryMockito(); CarFactoryMockito carFactorySpy = Mockito.spy(carFactory); Car mockedInstance = Mockito.mock(Car.class); Mockito.doReturn(mockedInstance).when(carFactorySpy) .carFactoryMethod(TESTING_TYPE, TESTING_COLOR); // invoke testing method Car actualInstance = carFactorySpy.constructCar(TESTING_TYPE, TESTING_COLOR); Assert.assertEquals(actualInstance, mockedInstance); // ... verify other logic in constructCar() method ... Mockito.verify(carFactorySpy, Mockito.times(2)).carFactoryMethod( TESTING_TYPE, TESTING_COLOR); } } Usage of PowerMock Before usage of this example, please carefully consider if it is worth to bring bytecode manipulation risks into your project. They are gathered in this blog post. In my opinion it should be used only in very rare and non-avoidable cases. Test shows how to mock constructor directly by PowerMock. Example covers: Mocking of constructor Verifying of constructor call Class under test: public class CarFactoryPowerMock { public Car constructCar(String type, String color) { new Car(type, color); return new Car(type, color); } } Test: /** * Demonstrates constructor mocking by PowerMock. * * NOTE: Prepared in PowerMock annotation {@link PrepareForTest} should be class * where is constructor called */ @PrepareForTest(CarFactoryPowerMock.class) public class CarFactoryPowerMockTest extends PowerMockTestCase { private static final String TESTING_TYPE = "Tatra"; private static final String TESTING_COLOR = "Black"; @Test public void testConstructCar() throws Exception { Car expectedCar = Mockito.mock(Car.class); PowerMockito.whenNew(Car.class) .withArguments(TESTING_TYPE, TESTING_COLOR) .thenReturn(expectedCar); // invoke testing method CarFactoryPowerMock carFactory = new CarFactoryPowerMock(); Car actualCar = carFactory.constructCar(TESTING_TYPE, TESTING_COLOR); Assert.assertEquals(actualCar, expectedCar); // ... verify other logic in constructCar() method ... PowerMockito.verifyNew(Car.class, Mockito.times(2)).withArguments( TESTING_TYPE, TESTING_COLOR); } } Links Source code can be downloaded from Github. Other unusual mocking examples: Mock private method Mock final method Mock final class Mock static method
March 11, 2014
by Lubos Krnac
· 98,112 Views · 7 Likes
article thumbnail
Spring Boot & JavaConfig integration
Java EE in general and Context and Dependency Injection has been part of the Vaadin ecosystem since ages. Recently, Spring Vaadin is a joint effort of the Vaadin and the Spring teams to bring the Spring framework into the Vaadin ecosystem, lead by Petter Holmström for Vaadin and Josh Long for Pivotal. Integration is based on the Spring Boot project - and its sub-modules, that aims to ease creating new Spring web projects. This article assumes the reader is familiar enough with Spring Boot. If not the case, please take some time to get to understand basic notions about the library. Note that at the time of this writing, there's no release for Spring Vaadin. You'll need to clone the project and build it yourself. The first step is to create the UI. In order to display usage of Spring's Dependency Injection, it should use a service dependency. Let's injection the UI through Constructor Injection to favor immutability. The only addition to a standard UI is to annotate it with org.vaadin.spring.@VaadinUI. @VaadinUI public class VaadinSpringExampleUi extends UI { private HelloService helloService; public VaadinSpringExampleUi(HelloService helloService) { this.helloService = helloService; } @Override protected void init(VaadinRequest vaadinRequest) { String hello = helloService.sayHello(); setContent(new Label(hello)); } } The second step is standard Spring Java configuration. Let's create two configuration classes, one for the main context and the other for the web one. Two thing of note: The method instantiating the previous UI has to be annotated with org.vaadin.spring.@UIScope in addition to standard Spring org.springframework.context.annotation.@Bean to bind the bean lifecycle to the new scope provided by the Spring Vaadin library. At the time of this writing, a RequestContextListener bean must be provided. In order to be compliant with future versions of the library, it's a good practice to annotate the instantiating method with @ConditionalOnMissingBean(RequestContextListener.class). @Configuration public class MainConfig { @Bean public HelloService helloService() { return new HelloService(); } } @Configuration public class WebConfig extends MainConfig { @Bean @ConditionalOnMissingBean(RequestContextListener.class) public RequestContextListener requestContextListener() { return new RequestContextListener(); } @Bean @UIScope public VaadinSpringExampleUi exampleUi() { return new VaadinSpringExampleUi(helloService()); } } The final step is to create a dedicated WebApplicationInitializer. Spring Boot already offers a concrete implementation, we just need to reference our previous configuration classes as well as those provided by Spring Vaadin, namely VaadinAutoConfiguration and VaadinConfiguration. public class ApplicationInitializer extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.showBanner(false) .sources(MainConfig.class) .sources(VaadinAutoConfiguration.class, VaadinConfiguration.class) .sources(WebConfig.class); } } At this point, we demonstrated a working Spring Vaadin sample application. Code for this article can be browsed and forked on Github.
March 10, 2014
by Nicolas Fränkel
· 13,519 Views
  • Previous
  • ...
  • 567
  • 568
  • 569
  • 570
  • 571
  • 572
  • 573
  • 574
  • 575
  • 576
  • ...
  • Next
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook
×