Mock a superclass method with Mockito

Say you want to test a method from class which extends some kind of superclass. Sometimes you can be dependent on code in the superclass, which is undesirable in a test.

Now actually, the first thing you should consider is to refactor your code, because it’s violating the Single Responsibility design principle:
there is more than one reason why your class is subject to change. Another advice is to favor composition over inheritence. In this way you can mock the code you are collaborating with.

Having said that, sometimes you run into legacy code you just have to work with and aren’t able to refactor due to circumstances. Here’s a trick to “mock” a superclass method to do nothing with mockito. Continue reading

Using ArgumentMatchers with Mockito

Mockito is a mock framework which you can use to write simple and clean tests. One of it’s nice features is the ArgumentMatcher. With the ArgumentMatcher you can determine the outcome of your mocked service or repository based on any condition you want.

Imagine we have a CandyService which can get a list of candies which are liked by a specific customer. This service uses the external ChocalateService which specifically checks if the customer likes chocolate. Continue reading

How to create (singleton) AngularJS services in 4 different ways

Next to creating controllers and directives, AngularJS also supports “singleton” services.
Services, like on the server-side, offer a great way for separating logic from your controllers.

In AngularJS anything that’s either a primitive type, function or object can be a service.

Although the concept of service is quite straight forward, the declaration of them in AngularJS isn’t:

  • There are 4 different ways to declare a service.
    • Registering a existing value as a service
    • Registering a factory function to create the singleton service instance
    • Registering a constructor function to create the singleton service instance
    • Registering a service factory which can be configured
  • Only 1 of them is extensively documented

The other 3 are only barely documentedThis post describes each option and when to use it in more detail.

Continue reading

Auto inject dependencies in JUnit using Mockito

While writing unit tests, you often have to mock dependencies like services or controllers. Often  a constructor is used to autowire the dependencies as shown in the example below. In the Test class I instantiated the ContactService using a contactRepository Mock object

@Service

public class ContactServiceImpl implements ContactService {
private final ContactRepository contactRepository;
    @Autowired
    public ContactServiceImpl(final ContactRepository contactRepository) {
    this.contactRepository = contactRepository;
    }
    public void saveContact(final Contact contact) {
    contactRepository.save(contact);
    }
}
The test class:
public class ContactServiceTest {

private final ContactRepository contactRepositoryMock = mock(ContactRepository.class);
private final ContactService contactService = new ContactService(contactRepositoryMock);
    @Test
    public void testSaveContact() {
    Contact contact = new Contact();
    contactService.saveContact(contact);
    //validate contactRepository.save is called
    verify(contactRepositoryMock).save(contact);
    }
}
In the previous example you always have to Autowire the constructor and bind the dependencies to the class variables. In the next example the code is cleaner by autowiring the mocking objects, so you don’t have to create a custom constructor or setters to set the dependencies, which makes your code more concise and easier to read.
@Service

public class ContactServiceImpl implements ContactService {
@Autowired
private final ContactRepository contactRepository;
    public void saveContact(final Contact contact) {
    contactRepository.save(contact);
    }
}
The test class:
@RunWith(MockitoJUnitRunner.class) //will initiate and inject the mocks

public class ContactServiceTest {
@Mock
private ContactRepository contactRepository; //Note the variable name must be exactly the same as used in ContactService
@InjectMocks
private final ContactService contactService = new ContactServiceImpl();
    @Test
    public void testSaveContact() {
    Contact contact = new Contact();
    contactService.saveContact(contact);
    //validate contactRepository.save is called
    verify(contactRepository).save(contact);
    }
}

Take a note of the “RunWith(MockitoJUnitRunner.class)” annotation. This annotation will initialize the annotated mock objects. An alternative is to use “MockitoAnnotations.initMocks(this)” in a setup method to initalize the annotated mock objects.

More tips can be found on the Mockito RefCard: http://refcardz.dzone.com/refcardz/mockito or take a look at the mockito site: http://www.mockito.org.

Compare JAR files content; decompiling class files

When I was recently working on a large restructuring and refactoring where I also replaced Ant by Maven, it was really necessary to compare the complete content of two different JAR files. It was required to know that the result of the restructuring and refactoring hadn’t changed the artifacts, thus the JAR files.
In the JAR files were different Class files present. When I compared the content of the two JAR files (with a binary compare) all the content was radically changed. This was partly because the compiler compiled the Class files at a different timestamp.

Since I wanted the best possible comparison between the two JAR files I needed to compare all Class files in the JAR by decompiling and comparing. This should give me a clearer and more honest picture of the differences. For this action I used Beyond Compare. By using an additional File Format (Java Class to Source) I was able to completely compare the decompiled Class files of the two JARS.

If you ever need to compare JAR, WAR or EAR files and need to compare the Class files inside; don’t try to unpack to a folder, decompile to a different folder and finally folder compare. You should use Beyond Compare and save time on comparing. The Beyond Compare license will pay itself off.

Using URL Scheme for Telephone Numbers in HTML

We can use the tel: URL scheme for phone numbers in HTML. Just like the mailto: URL scheme will open the default mail application will the tel: start a telephone call. If the HTML page is viewed on a mobile phone and we select a link with the tel: scheme we can immediately call the number following the scheme. On a desktop computer a VOIP call will be initiated.

We can use hyphens in the phone number for readability, they will be ignored when the call is made. For example the imaginary phone number 123456789 in the Netherlands can be used as shown in the following HTML snippet:

More information is available at http://www.ietf.org/rfc/rfc3966.txt.

Original post

javax.xml.bind.JAXBException: “package” doesn’t contain ObjectFactory.class or jaxb.index

Once in a while we have those small issues which still can take some hours of our day. For example last week I was configuring a Spring JAXB2Marshaller using the context below:

<bean id="jaxb2Marshaller">
<property name="contextPaths">
<list value-type="java.lang.String">
<value>nl.jdriven.myproject.package.with.a.very.long.name
</value>
<value>nl.jdriven.myproject</value>
</list>
</property>
</bean>

However when running my JUnit test using this context the following exception occurred:

It look liked something was wrong with my generated JAXB project. Unfortunately I needed some hours to notice that maybe the break line in the value element of the contextPathslist could cause the issue

After changing the spring-context.xml as below, moving the </value> tag inline, the JAXB2Marshaller worked perfectly.

<bean id="jaxb2Marshaller">
<property name="contextPaths">
<list value-type="java.lang.String">
<value>nl.jdriven.myproject.package.with.a.very.long.name</value>
<value>nl.jdriven.myproject</value>
</list>
</property>
</bean>

Apparently the spring-context is sensitive to break lines when we configure the Jaxb2Marshaller context paths. Due to my habit of using the Eclipse format shortcut Ctrl + Shift + F the formatter kept moving the end tag of the context path to a newline.

We can prevent this issue by changing the settings of your Eclipse XML editor settings. In your Eclipse click Window -> Preferences -> XML -> Editor and set the line width to e.g. 140.

The Quick & Dirty Fraud

If you have a car, then every once in a while, you probably have your vehicle checked to see if it’s still up to safety and environmental standards.

So you take your car to the garage and have it checked. Now, the garage will do some tests and eventually you’ll get a nice paper showing what kind of maintenance they have done.

Nowadays, cars are complex, computerized machines. (The days of dad lying under the car to do some fixing with some elemental tools are all but gone.) This means that as a customer, you will have to rely on the professional capabilities and integrity of the garage. You’ll have to trust that if the garage says the car is fixed and okay, it really is fixed and okay.

Now imagine that you went to the garage, received the paper that your car is okay, go on the road, and your car breaks down. What would be your reaction? You’d probably hold the garage responsible for this, as they are the experts and you paid them to do a good job. What would your reaction be if they told you that they didn’t have time to correctly solve your cars problems and did a ‘quick fix’, without them telling you?

In software development I frequently come across similar situations. Companies hire in IT solution providers, to help them solve their IT related problems and deliver high quality solutions for their business. Now software products and projects tend to be very complex and therefore, customers will, one way or another, have to rely on the professional capabilities and integrity of the solutions provider (or the solutions provider, checking the solutions provider).

How then would we label deliberate quick ‘n dirty fixes by developers, just to get the project ‘done’, leaving the customer with piles of technical debt?

It is the responsibility of solutions providers and professional developers, to point out the consequences of quick ‘n dirt fixes. A good solutions provider therefore will, out of professional honor and integrity, have the courage to point out the severe consequences and even refuse quick ‘n dirty fixes, knowing that in the end, low quality won’t pay off.

Quality isn’t negotiable and long after the ‘quick’ has been forgotten, the ‘dirty’ will probably still be there.

Original article

SpringOne 2012 essence

So what to take away from the SpringOne 2012 conference?
The overall theme of this conference is the changing world we as developer find ourselves in. As we all know the world of software development is always evolving at a rapid pace. This evolution always leads to changes in requirements and new solutions to breach the gap. In some cases these evolutions require a new way of thinking. The essence of this SpringOne is about the latter. The current evolution is driven by:

  • increases in data quantity
  • the explosion of browser enabled devices
  • the request for higher quality of service (an application needs to be able to survive outage of a data center)
  • near real time delivery of contextual information and social integration in frontends.

The combination of these new demands and requirements leads us to a so-called paradigm shift. These problems cannot be solved with past (or current) architecture. So we need to look at our applications in a new way. Building and modularizing them to account for scalability because that seems to be the answer to the questions asked.

We need to start thinking in federations to persist information across cloud instances. Size and package application modules so they can be scaled separately.
At his SpringOne conference the tools and the methods needed to do this were show cased. Adrian Colyer’s keynote on day two gives us a good idea of what Spring offers to help us cope with these changes and as always make our life easier.

You can view the full keynote here:
http://www.springsource.org/SpringOne2GX2012
or download the sheets: http://springone2012.s3-us-west-1.amazonaws.com/SpringOne2GX_2012_Keynote-Day-2_Final.pdf

As for some examples of tools that help you deal with these impending changes check out the VMware en SpringSource projects below: