Samstag, 10. Dezember 2011

Mockito the Java Standard Mocking Framework?

I used a long time JMock and I really love it, I also used a lot EasyMock because of the answer and capture feature. About a year ago I found the mocking framework mockito. After that I was able to inspire a few work colleagues to use mockito in their projets. I play around with it again and my conclusion is: Mockito is at the moment the best mocking framework for Java and I'm not alone.

"We decided during the main conference that we should use JUnit 4 and Mockito because we think they are the future of TDD and mocking in Java" - Dan North, the originator of BDD

Mockito has a clean syntax and the patterns and ideas behind mockito make tests more maintainable. Mockito has the power of EasyMock but a smarter syntax. Today I build for my self a simple JUnit test as mockito cheat sheet. So you convince yourself with Mockito and the smart API see the demo test bellow.


Links
  • Mockito Project Site
    http://code.google.com/p/mockito/
  • Documentation Mockito
    http://docs.mockito.googlecode.com/hg/latest/org/mockito/Mockito.html
  • GitHub Project with the Cheat Sheet Test
    https://github.com/tux2323/mockito-cheat-sheet

Mittwoch, 23. November 2011

Test Doubles and Mocking Patterns

Yesterday I refactored a unit test with over 2000 lines of code, now the test has around 900 lines of code. One pattern I found in the test was that for every kind of test double a mock object was used.

I prefer the following test design rule for mock objects and test doubles. Object which contains logic e.g. of type service, factory or repository should be mocked instead of DTOs, value objects or entities (plain Java Beans) with getters and setters e.g. configuration objects this kind of object should never be mocked.

Here small example, a test with to much mocking, please don't write such kind of tests:


This simple unit test above has to much mocking logic and should be refactored to this test:


If you like you could use the builder pattern for the simple objects like sale to get the test a little bit nicer (see the links for eclipse tooling). A smell is when you need to mock classes, in most cases then you should use another test double pattern for this kind of objects, or something with the design of the SUT is wrong.

What I like to say is you should not always use our preferred mocking framework to create a mock object as test double for everything. There are situations where mock object I believe are a test design anti pattern / smell. Think about stubs and dummy object before creating a mock object and read the great xUnit test pattern book “xUnit Test Patterns” from Gerard Meszaros. Then you are on the right way to get an agile tester ;-)

Links

Donnerstag, 17. November 2011

OSGi Users' Forum Germany Community Event 2011

This year the OSGi UFG Event was based in Cologne. The event was great a lot of new input. My favorite topics were PojoSR and OBR (OSGi Bundle Repository). A great podiums discussion on OBR there was a great discussion about commercial bundle repositories "App Store for Bundles".

Richard Nicholson (OSGi Alliance President) could not make it to event, because he has an important meeting in UK . So we shortly changed the Keynote "OSGi Alliance Update" to "OSGi Community Update". In this session I tried to give an overview what happens in the OSGi World/Community in the year 2011. I believe I missed a lot of stuff, but when I prepared the session I become the feeling 2011 was a lot of work in OSGi Community done. I think OSGi was not much in the news but a lot of new open source projects and also a lot of progress in the OSGi specification was done. For example the enterprise specification was finished, the OSGi Core specification 4.3 was released in April, the package admin is now deprecated, we have now a much better API the Wire API. Also in the tooling area much happens in this year. I think BNDTools could become the standard tooling for OSGi. Hope Neil well release the BNDTools Version 1.0.0 this week ;-)


The first session on the UFG was about OSGI in Healthcare applications and smart cards. The talk covers the n-pad product which is used for the German "Gesundheitkarte". Stephan Hoffmann-Emden and Andreas Klotz shows in short live demo how there OSGi based smartcard reader works. They have built a PKI Service for their OSGi platform. Is there a standard for PKI / crypto handling in OSGi?


In the next session Andreas Kraft cover the topic "OSGi in the Residential Market". Andreas gives a good overview which topics will be in the OSGi Residential specification. The talks give also a short introduction in the OSGi Alliance Processes e.g. what is an RFP and so on.

After a small coffee break Holger Hoffstätte gives a really nice overview on OBR. His statement the important thing about OBR is the model. I think OBR will fix a lot of problems in OSGi tooling and deployment. I think it will also play a rule in the SEITENBAU OSGi projects. OBR solves a lot of problems we have at SEITENBAU and we now have solved by custom solutions. So we need it right now.


In the podiums discussion "OSGi Bundle Repository versus Apache Maven Repository" we have lot of good discussion. Okay the title was not perfect ;-).

First session in the second track after launch was PojoSR my favorite session. Karl Pauls explains why we need PojoSR and how to migrate Projects to OSGi by using PojoSR. He also covers very well the problems when migrating existing projects to OSGi. I think Pauls statement is absolute true PojoSR brings µServices to the rest of us.


Ralf Sternberg and Frank Appel shows with a great live demo how to use RAP with OSGi. They also explains how RAP application benefit by using OSGi. I didn’t know the actual RAP Version is based on OSGi services and do not use the eclipse plugin registry. I hope will have a little free time to try and play around with the actual RAP version. In the session Ralf and Frank shows also a RAP based smartphone client.

After the RAP session Stefan Kachel introduce the eclipse project Riena. Riena makes the SWT UI development much easier. There is also an eclipse toolbox provided by the Riena project, which makes the development of Riena based applications much easier. Stefan shows how to use Riena by a running example application.

Kai Hackbarth gives a session about "OSGi for In-Vehicle Systems". He explains how car sellers benefit by using OSGi as basic platform for the products. In the session Kai gives also a nice overview of the alternative platforms like android which are used in vehicle systems. Good news there are already OSGi deployments, Kai gives some examples where OSGi is already deployed.


Last but not least a really cool session on the topic how normal web application could benefit by using OSGi from Jan Ehrhardt. Jan shows the reality, the problems and why in many cases normal web applications not benefit by using OSGi. In the second part of his session he shows in which situations and how web application could benefit by using OSGi. In the last part of his session he shows how OSGi could be used in different Java EE environments e.g. embedded in tomcat, next generation EE applications server or OSGi as standalone application e.g. by using Apache Karaf.


Was again a great Users Forum Germany community event with great sessions thanks to the audience and the speakers. Only the date was not perfect chosen there where parallel in London UK a face to face meeting. Next time we will make it better I believe ;-)

In next couple of day I will make the last slides available I hope via slideshare and I will also linkt the link to the slides from the UFG website.

Links
http://germany.osgiusers.org/Main/OSGiUFGTreffen2011
http://www.slideshare.net/OSGiUsers

Sonntag, 30. Oktober 2011

Spring Dependencies Structure

Based on the "Diagram of Spring 3.0 module dependencies" from Osvaldas Grigas and the spring poms I made a simple yUML diagram. The diagram gives a short overview of the spring components and there dependencies. The green marked component is the core functionality of spring. The blue marked components provides functions based on the spring core.

Here the source of the yUML diagram, if you like to add some aspects or change something feel free and reuse it.

Links

Donnerstag, 27. Oktober 2011

Spring Customize Annotation Scanning

A really nice feature in Spring 3.0 is to have custom annotation. Why do you like to have own annotations? Because you could provide some semantic details about the component types. For example when you have a spring bean which is facade, why not use a annotation with the name facade?

Here the spring wiring for beans with the annotation facade:

The facade annotation:

And here a demo facade spring bean:

Spring DI with Java Standard Annotations

In Spring it is easy to use the Java annotations for dependency injection (JSR 330), the Java annotation for post construct and pre destroy (JSR 250) and the Java API and Annotations for validation (JSR 303).

Why should I use this standard APIs and annotation in a Spring based application? Because when using this standards, the code has only dependency on standard APIs (javax). And the code could also be used in another implementation e.g. of the JSR 330.

Here a simple code snippet, which shows how to use this three Java standards in a spring bean.



And here the spring context configuration.


You could also mix the Spring annotations with the JSR 330 annotation. I think a good strategy is to use the JSR 330 annotation when every its possible and makes sense. In some cases you would use the spring specific annotations.

Which annotations do you prefer to use in a Spring application?

For more details see the spring documentation:
http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/

Dienstag, 25. Oktober 2011

OSGi - How to get the Bundle Context in a Java Object Instance

In most cases I use DS components, when I need the bundle context instance, the DS Framework injects me the bundle context in the activation method of my component. In most components I don’t like to have a dependency on OSGi APIs in my DS components, but thats another topic.

But sometimes I need an OSGi service or the BundleContext also in non OSGi / DS controlled class. E.g. when I like to write a JAX-WS web service class. There are many ways to get the Bundle Context into this type of Objects. One is to get the Bundle Context from the ClassLoader (which should implements the BundleReference interface). Here a short demo code snippet how to get the bundle API and also the bundle context of a class.



Comment: "However, this requires the code to have the permission to access the class loader." OSGi Core Specification see section 3.8.9.

Better implementation (thanks at Holger for the hint) is by using the OSGi FrameworkUtil class. See the second code snippet:



Another solution could be a holder class with a static field, which holds the actual bundle context instance. This also works when the code does not have the permission to access the class loader.

Montag, 17. Oktober 2011

OSGi RFC-0172 Declarative Services Annotations Runtime?

I had with Peter Kriens and Neil Bartlett on Twitter an interesting discussion about "Why the DS annotations in the DRAFT RFC-0172 Declarative Services Annotations should be process at runtime or compile time".

Here in this post I like to show my opinion why to process annotations at runtime.

Runtime Annotations kills DS lazyness?
Peter says at twitter "One of the best things about DS is its lazyness, we do not want to kill this".

My option is that with runtime annotations we do not kill the DS lazyness.
I think we do not need to scan the bundles classes and load them all, to find the DS components in the system. The simplest solution is to have the components with the full qualified class name in the bundle MANIFEST.MF here a sample code snippet:



The next thing is we need a way to read the annotations without loading the class into the class loader to support bundles e.g. with "Bundle-ActivationPolicy: lazy". All information for the DS model is in the system in the byte code (when we use runtime annotations). Because of that, we can read the information for the DS components from the bytecode. Reading annotations from the bytecode is a simple way to provide all the lazyness we have with the XML model. To show this I create a very simple prototype which use the javassist library to process the annotation at runtime in a OSGi framework see https://github.com/tux2323/annotation.processing.osgi/.

Reading Annotations at Runtime is a Performance Issue?
Peter says: "So byte code scanning does not take any time?"

XML reading at runtime does also take time; do you think reading XML can be done faster than reading byte code? All information are in the byte code is reading the byte code really a performance issue? I believe we could make reading the information for the DS components from the byte code almost as fast as reading it from the XML files.

Detect errors early?
Another statement from Peter pro XML model for DS is "Detect errors early".

Yes when the annotation is process at runtime, we won’t also have a static testing tool like bnd which checks at compile time, if everything is okay with the model and shows the problems in the IDE. Why do we need the XML model for doing this?

Why runtime Annotation?
Neil asked me on Twitter "Why would you do at runtime what you can do better at build time?".

My statement is: I would like to process the annotations at runtime, because I don't like to have information in two places in my system, only when there are technical reasons, for doing this. Because of that I think it would be nice to have runtime annotations.

When we have runtime annotations then the SCR Implementation can also decide to support them at runtime or generate at build time the XML Model e.g. via bnd. The most Java frameworks (EJB3, JAXB, JAX-RS...) use runtime annotations for their components, why do OSGi like to go a different way?"

XML and Annotations
Neil asks me on twitter "Sorry I don't understand. You want the runtime to look at both the annotations *and* the XML?"

Short answer: yes.

Long answer: When we support runtime annotations to describe DS components, which should be process at runtime, we must also support the old XML way to be backward compatible. So I like to have both XML and annotations like in the Spring framework. In Spring you could describe a bean via XML and if you like you can describe the spring bean by annotations.

Thanks
Thanks at Neil and Peter for the great discussion. At this point again I would like to say when you use at the moment DS you should use the cool annotations from BND. This is at the moment the best way to develop DS components, I think.

Links

Samstag, 15. Oktober 2011

JUnit > 4.10 Rules

It's been a long time ago that I last wrote about JUnit. A number of improvements and releases have been made. There have been lot improvements around the topic JUnit rules added. Today I had little bit free time to look into this new JUnit features.

Class Rules
Now there are also class rules in JUnit. A class rule extends the idea of test method-level rules and can be used to add logic, which should be invoked for or after all test methods. A simple use-case could be, when you need a HTTP server in the test, you could have a class rule to start and stop the server. Here a simple code snippet that starts and stops a HTTP server.



Test Sequence
  1. Start HTTP Server
  2. Run Test : invokeServletWithRequestOne()
  3. Run Test : invokeServletWithRequestTwo()
  4. Stop HTTP Server


Composition of JUnit Rules with RuleChain Feature
In JUnit 4.10 now you can order rules via a rule chain. This is really nice to reuse rules and combine them. Here a simple RuleChain code snippet.



Test Sequence
  1. Start new Jetty Server (rule = ServerRule)
  2. Create new Servlet Instance and add it to the Server (rule = ServletRule)
  3. Run Test : invokeServletWithRequestOne()
  4. Remove Servlet from Server (rule = ServletRule)
  5. Stop Jetty Server (rule = ServerRule)
  6. Start new Jetty Server (rule = ServerRule)
  7. Create new Servlet Instance and add it to the Server (rule = ServletRule)
  8. Run Test : invokeServletWithRequestTwo()
  9. Remove Servlet from Server (rule = ServletRule)
  10. Stop Jetty Server (rule = ServerRule)


Interface MethodRule is deprecated
The type MethodRule is now deprecated because the name makes no sense anymore because now we have class and method-level rules. A rule now should be of the type TestRule.

Thanks
Thanks at David Saff and Kent Beck for the work on JUnit and the cool rule features we have now in JUnit.

Links

Donnerstag, 13. Oktober 2011

OSGi Declarative Service Naming and Implementation Patterns

Here some simple OSGi declarative service (DS) naming and implementation patterns I prefer to use.

1. Naming Pattern - Component Name
A DS component name should end with Component e.g. RobotComponent.

public class RobotComponent implements Robot {}

2. Naming Pattern - Start and Stop Method
For methods, which should be called on, activate or deactivate a DS component the following names should be used:
  • start(…) and stop(…)
  • startup(…) and shutdown(…)
  • initialize(…) and deinitialize (…)
  • activate(…) and deactivate(…)

public class RobotComponent implements Robot {
      public void activate(){...}
      public void deactivate(){...}
}

3. Naming Pattern - Service Lifecycle Methods
For the service lifecycle method the following method name patterns should be uses:
  • bind${serviceName}(…) and unbind${serviceName}(…)
  • set${serviceName}(…) and unset${serviceName}(…)
  • add${serviceName}(…) and remove${serviceName}(…)
e.g. void bindRobot(Robot robot) and unbindRobot(Robot robot)


DS method name for bind more then one service instance 0..n or 1..n should become the name add* and remove*.

public class RobotComponent implements Robot {
      public void setEngine(Engine engine){...}
      public void unsetEngine(Engine engine){...}
      public void addSensor(Sensor sensor){...}
      public void removeSensor(Sensor sensor){...}
}


4. Implementation Pattern - Behavior Symmetry
When there is logic for start (activate) or set something there should always be logic for stopping or unset.

5. Implementation Pattern - Avoid Implicit Immediate Components
When a DS component not provide a Service then the component is immediate activate when all reference service are available. When the code is changed and the component know provide a service, then the component is activated when the first client component like to use the service. When a component should be activate immediate then I think avoid implicitly immediate components add always immediate=true.

6. Implementation Pattern - Use Annotations for DS Components
Use BND or Apache Felix SCR annotations to describe DS components.

Links

Mittwoch, 12. Oktober 2011

10 min - Domain Driven Design (lightning talk )

Here my slides from my lightning talk about Domain Driven Design. The slides I have not really needed in the lightning talk. Because my notebook crashed and I only could show slide number one. And because of that I only used the first slide. With the first slide I give a 10 minutes overview of domain driven design, keywords, patterns and core ideas. I think this basics ideas behind domain driven design every software developer should know.


I think the following patterns, keywords and ideas should be known by everyone how developed OO software:
  • Ubiquitous Language
  • Domain
  • Domain Layer
  • Entities
  • Value Object
  • Repository
  • Aggregate
  • Service
  • Factory (e.g. Dependency Injection, Spring, Google Guice...)
  • Assertion
  • ...
For those who could not be in my lighting talk, should have a look at the domain driven demo application. Everyone should have read the book by Eric Evans about Domain Driven Design. Okay the book is not update at all, but I think the most stuff in the book is still correct.

Links and Ressources

Samstag, 24. September 2011

Seitenbau Developer Convention 2011 - Getting started with Scala

A week ends now the SDC = Seitenbau Developer Convention is over. Was a cool event again learned a lot about web development html5 with boilerplate, CouchDB, oAuth2, Android development, Gerrit and Skali.

Together with Dennis, I told a bit about the Scala language. Here are the slides of this Scala session


More about the SDC can be found here (there is also an android app in the android market)
https://www.seitenbau.com/sdc/timetable

Getting started with OSGi using a 3D OSGi Robot at OSGi Community Event 2011

The OSGi Community Event 2011 in Darmstadt was a really cool OSGi conference at all. Thanks for the organizationof this nice Event and the lots of new ideas, comments and inputs from all the participants.

Here the slides of Jochen and my Mars Robot session.

And here the slides from the session about the Platform O.N.E.


More information’s about the sessions and also the slides can be found here
http://www.osgi.org/CommunityEvent2011/Agenda

Sonntag, 31. Juli 2011

JMock HasProperty Expectations

Took me a while to define JMock expectations which verifies that a argument of mocked method has a defined set of properties with values.

Here my JMock based JUnit test:


Is there no better way to do this in JMock?

Donnerstag, 16. Juni 2011

Top 10 Software Engineering Books – Must Read

Today I gave a lighting talk at SEITENBAU, about my favorite top ten software engineering books. Here my top ten list of books, which every developer should read:

#1 - Andrew Hunt, David Thomas - The Pragmatic Programmer - From Journeyman to Master

#2 - Erich Gamma, Richard Helm, Ralph E. Johnson, John Vlissides - Design Patterns

#3 - Martin Fowler - Refactoring -Improving the Design of Existing Code

#4 - Eric Evans - Domain Driven Design

#5 - Kent Beck - Test Driven Development by Example

#6 - Alistair Cockburn - Writing Effective Use Cases

#7 - Scott Berkun - The Art of Project Management

#8 - Martin Fowler - Patterns of Enterprise Application Architecture

#9 - Joshua Bloch - Effective Java

#10 - Gerard Meszaros - xUnit Test Patterns

I think there are more books you should read as a professional developer, but this list is at the moment my top ten list of books I think should have read.


What are your favorite software engineering books? Send me comments or write me via Twitter.


Links

Sonntag, 5. Juni 2011

Sikuli – GUI Test Automation with Java Robot API and Images

The Sikuli project provides a simple tool for automate and test graphical user interfaces (GUI) using images (screenshots). The idea is to find an element on the screen by a screenshot and not by XPath or ID. The tool can be used for all GUIs also web applications. It’s a nice idea below you can see a simple example.


The SIKULI project is based on the Java VM and also provides an API for writing the automation in Java here a JUnit sample test.


For real world web testing it is not the right tool I think, because it depends on the style of the elements. When the button style changed you need a new screenshot of the button. But it is a nice tool for simple automation tasks. Have also a look at screen casts on the project homepage.

Links:
- Project Home - http://sikuli.org/
- How to use Sikuli Script in your JAVA programs - http://sikuli.org/docx/faq/030-java-dev.html

Convert a simple CSV File with Groovy, Java, Scala, awk, Ruby, Python, PHP or Bash?

Change Log:
  • 05.06.2011 1:30 pm - Initial created Post with  Groovy, Java, Scala, awk, Ruby, Python Implementation
  • 05.06.2011 4:00 pm - Add PHP implementation and update voting (now you can vote for PHP).
  • 06.06.2011 4:00 pm - Add Bash implementation and update voting (now you can also vote for Bash)

Which is the best programming language for converting a simple CSV into another format?

First I blogged three Java VM based solutions written in Groovy, Java and Scala to convert a simple CSV file into another format. Rainer sends me the Java based solution, yesterday Axel Knauf sends an awk based solution, Niko sends Ruby based solution, Hendrik sends a Python based solution, Sebastian sends me a PHP implementation and Julien sends a Bash version. Now there are a Groovy, Java, Scala, awk, Ruby, Python, PHP and Bash implementation.

Now here again a complete overview of the different implementations:

The Groovy Implementation:

The Java Implementation:

The Scala Implementation:

Here the shell command and awk script:

The pure Ruby Implementation:

The Python Implementation:

The pure PHP Implementation:

The Bash Implementation:


I'm curious whether there are other implementation proposals (Clojure, Perl, PHP, …), if you have one you could send me the script via Twitter or leave a comment here…

I am also curious which implementation Groovy, Java, Scala, awk or Ruby you like and why? I have create voting here:


Thanks Rainer, Axel Knauf, Niko Dittmann, Hendrik Heimbuerger S.Barthenheier and Julien Guitton for the Java, awk, Ruby Python, PHP and Bash implementation.

Links:

Convert a CSV File with awk

Yesterday I post three Java VM based solutions written in Groovy, Java and Scala to convert a simple CSV file into another format. Today kopfkind sends me via Twitter a awk based solution.

Here the shell command and awk script to convert the CSV file:

Thanks a lot @kopfkind for this simple solution. I'm curious whether there are other implementation proposals (Python, Clojure, Perl, Bash, PHP, …), if you have one you could send me the solution via Twitter or leave a comment here.

I am also curious which implementation Groovy, Java, Scala or awk you like and why?

See also: Convert a CSV File in Groovy, Java or Scala?

Samstag, 4. Juni 2011

Convert a CSV File in Groovy, Java or Scala?

Last week I have simple task I must convert a simple CSV file into another CSV format. My first solution was a simple Groovy script. Then inforw sends me a Java solution, to show me that with Java it is no much more code then the Groovy implementation is. Today I wrote just for fun a solution in Scala, to see how the code looks in Scala. My favorite of the three implementations is at the moment the Groovy one. But I think the Scala implementation has the best readability. Below you see the three implementations.

I'm curious what you like, feel free for comments? And I would be glad if someone contributes even further implementation in Clojure, Python, Perl,… or even a better Scala, Java or Groovy implementation.

The Groovy Implementation:

The Java Implementation:

The Scala Implementation:

Thanks @inforw for the discussion and the Java implementation.

Freitag, 3. Juni 2011

Test Logging via JUnit Rule

In most cases it is not necessary to test logging, but in some situations you wont to check in a JUnit test that a log statement will be written, e.g in special error cases. When you use logback as logging framework the test can setup a ListAppender for a Logger and can implement a assert method which checks that the expected log statement is in the ListAppender list. But then the test is logback specific and has dependency on logback! When you use this approache in many JUnit test classes the test source has a hard dependency on logback and when you wont to change the logging framework all tests must also be changed. To remove this hard dependency you can use a JUnit rule, which capsulate the logback framework from the test source. The example here shows how a test and such a JUnit rule can look like.

Here the sample test for verify logging:


And here the logback specific rule:

Donnerstag, 2. Juni 2011

Logging in JUnit Tests

With a JUnit 4.7 rules it is easy to add logging support in JUnit tests. The example test bellow shows how to add simple logging for each test method and the result of the test.



For more details about logging in JUnit tests see the blog post "JUnit 4 Test Logging Tips using SLF4J".