Coding

Change return value of mocked or stubbed service based on argument value with Spock

Posted on by  
Hubert Klein Ikkink

Albert van Veen wrote a blog post about Using ArgumentMatchers with Mockito. The idea is to let a mocked or stubbed service return a different value based on the argument passed into the service. This is inspired me to write the same sample with Spock. Spock already has built-in mock and stub support, so first of all we don’t need an extra library to support mocking and stubbing. We can easily create a mock or stub with the Mock() and Stub() methods. We will see usage of both in the following examples. In the first example we simply return true or false for ChocolateService.doesCustomerLikesChocolate() in the separate test methods.

import spock.lang.*

public class CandyServiceSpecification extends Specification {

    private ChocolateService chocolateService = Mock()
    private CandyService candyService = new CandyServiceImpl()

    def setup() {
        candyService.chocolateService = chocolateService
    }

    def "Customer Albert really likes chocolate"() {
        given:
        final Customer customer = new Customer(firstName: 'Albert')

        and: 'Mock returns true'
        1 * chocolateService.doesCustomerLikesChocolate(customer) >> true

        expect: 'Albert likes chocolate'
        candyService.getCandiesLikeByCustomer(customer).contains Candy.CHOCOLATE
    }

    def "Other customer do not like chocolate"() {
        given:
        final Customer customer = new Customer(firstName: 'Any other firstname')

        and: 'Mock returns false'
        1 * chocolateService.doesCustomerLikesChocolate(customer) >> false

        expect: 'Customer does not like chocolate'
        !candyService.getCandiesLikeByCustomer(customer).contains(Candy.CHOCOLATE)
    }

}

Continue reading →

Mock a superclass method with Mockito

Posted on by  
Arthur Arts

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 I found on Stackoverflow to “mock” a superclass method to do nothing with mockito.

public class BaseController {

     public void method() {
          validate(); // I don't want to run this!
     }
}
public class JDrivenController extends BaseController {
    public void method(){
        super.method()
        load(); // I only want to test this!
    }
}

@Test
public void testSave() {
    JDrivenController spy = Mockito.spy(new JDrivenController());

    // Prevent/stub logic in super.method()
    Mockito.doNothing().when((BaseController)spy).validate();

    // When
    spy.method();

    // Then
    verify(spy).load();
}

Continue reading →

Nifty JUnit : How to test for an exception

Posted on by  
Willem Cheizoo

Testing for exceptions in JUnit is something we have to deal with! We want to test if an exception occurs in a particular situation, or even if the exception contains a particular message. The question is: How to test for an exception in Junit? What we see very often is this:

import org.junit.Test;

public class JDrivenServiceTest {

    JDrivenService service = new JDrivenService();

    @Test(expected = ArticleNotFoundException.class)
    public void testPublishArticle_WithException() throws Exception {
        service.publishArticle(null);
    }
}

Continue reading →

Using ArgumentMatchers with Mockito

Posted on by  
Albert van Veen

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. The CandyServiceTest class looks like this:

@RunWith(MockitoJUnitRunner.class) // will initiate and inject the mocks

public class CandyServiceTest {

    @Mock
    private ChocolateService chocolateService;

    @InjectMocks
    private CandyService candyService = new CandyServiceImpl();

    @Test
    public void testCustomerLikesChocolate() throws ParseException {
        Customer customer = new Customer();
        customer.setFirstName("Albert");
        List candiesLikedByCustomer = candyService.getCandiesLikeByCustomer(customer);
        assertTrue(candiesLikedByCustomer.contains(Candy.CHOCOLATE), "Expected customer to like chocolate");

    }

    @Test
    public void testCustomerWhoNotLikesChocolate() throws ParseException {
        Customer customer = new Customer();
        customer.setFirstName("Any other firstname");
        List candiesLikedByCustomer = candyService.getCandiesLikedByCustomer(customer);
        assertFalse(candiesLikedByCustomer.contains(Candy.CHOCOLATE), "Expected customer not to like chocolate");

    }
}

Continue reading →

Grails Goodness: Injecting Grails Services into Spring Beans

Posted on by  
Hubert Klein Ikkink

One of the underlying frameworks of Grails is Spring. A lot of the Grails components are Spring beans and they all live in the Spring application context. Every Grails service we create is also a Spring bean and in this blog post we see how we can inject a Grails service into a Spring bean we have written ourselves. The following code sample shows a simple Grails service we will inject into a Spring bean:

// File: grails-app/services/com/mrhaki/sample/LanguageService.groovy
package com.mrhaki.sample

class LanguageService {

    List<String> languages() {
        ['Groovy', 'Java', 'Clojure', 'Scala']
    }

}

Continue reading →

Auto inject dependencies in JUnit using Mockito

Posted on by  
Sjoerd Schunselaar

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);
    }
}

Continue reading →

javax.xml.bind.JAXBException: "package" doesn't contain ObjectFactory.class or jaxb.index

Posted on by  
Albert van Veen

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:

java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jaxb2Marshaller' defined in class path resource \[test-savings-online-direct-export.xml\]: Invocation of init method failed; nested exception is org.springframework.oxm.UncategorizedMappingException: Unknown JAXB exception; nested exception is javax.xml.bind.JAXBException: " nl.jdriven.myproject.package.with.a.very.long.name
                                                  " doesnt contain ObjectFactory.class or jaxb.index

Continue reading →

Consume REST JSON webservices easily using Spring Web!

Posted on by  
Sjoerd Schunselaar

Spring made it very easy to consume JSON webservices. In this article I describe how to receive and parse JSON and how to send your Java objects as JSON. First we need to include the required dependencies. If you use maven, include the following dependencies:

<dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>3.1.2.RELEASE</version>
</dependency>
<dependency>
      <groupId>org.codehaus.jackson</groupId>
      <artifactId>jackson-mapper-asl</artifactId>
      <version>1.9.9</version>
</dependency>

Continue reading →

Javascript, keeping it clear

Posted on by  
Richard Rijnberk

Note that this blog is in no way written as a "best practice" or "do it this way" kind of blog. I am not, nor do I aspire to be, the worlds greatest javascript programmer. I do however like my code clear and structured. Now lately some collegues have asked me how I write my code and that in turn prompted this blog. In short the best way to keep your javascript clear is using namespaces. The use of namespacing is very simple and should cause you no problems. As you will come to see it will be both easy and clear for fellow developers to read and modify your code. So yes, if you wish to remain the javascript magician with obscure code that no other developer wants to touch feel free to not use them. Creating a namespace:

var namespace ={
}

Continue reading →

Gradle Goodness: Distribute Custom Gradle in Our Company

Posted on by  
Hubert Klein Ikkink

The Gradle wrapper allows us to let developers use Gradle without the need for every developer to install Gradle. We can add the output of the Gradle wrapper task to version control. Developers only need to checkout the source for a project and invoke the gradlew or gradlew.bat scripts. The scripts will look for a Gradle distribution and download it to the local computer of a developer. We can customize the Gradle wrapper and provide a different source for the Gradle distribution. For example we can add the Gradle distribution ZIP file on our company intranet. We then use the distributionUrl property of the Wrapper task to reference the intranet location where we place the Gradle distribution ZIP file.

In the following sample file we use the distributionUrl property to reference our company intranet:

Continue reading →

Groovy Goodness: Pretty Print XML

Posted on by  
Hubert Klein Ikkink

The easiest way to pretty print an XML structure is with the [XmlUtil](http://groovy.codehaus.org/api/groovy/xml/XmlUtil.html) class. The class has a serialize() method which is overloaded for several parameter types like String, GPathResult and Node. We can pass an OutputSteam or Writer object as argument to write the pretty formatted XML to. If we don't specify these the serialize() method return a String value.

import groovy.xml.*

def prettyXml = '''
<?xml version="1.0" encoding="UTF-8"?>
<languages>
  <language id="1">Groovy</language>
  <language id="2">Java</language>
  <language id="3">Scala</language>
</languages>
'''


// Pretty print a non-formatted XML String.
def xmlString = '<languages><language id="1">Groovy</language><language id="2">Java</language><language id="3">Scala</language></languages>'
assert XmlUtil.serialize(xmlString) == prettyXml

// Use Writer object as extra argument.
def xmlOutput = new StringWriter()
XmlUtil.serialize xmlString, xmlOutput
assert xmlOutput.toString() == prettyXml

// Pretty print a Node.
Node languagesNode = new XmlParser().parseText(xmlString)
assert XmlUtil.serialize(languagesNode) == prettyXml


// Pretty print a GPathResult.
def langagesResult = new XmlSlurper().parseText(xmlString)
assert XmlUtil.serialize(langagesResult) == prettyXml


// Pretty print org.w3c.dom.Element.
org.w3c.dom.Document doc = DOMBuilder.newInstance().parseText(xmlString)
org.w3c.dom.Element root = doc.documentElement
assert XmlUtil.serialize(root) == prettyXml


// Little trick to pretty format
// the result of StreamingMarkupBuilder.bind().
def languagesXml = {
    languages {
        language id: 1, 'Groovy'
        language id: 2, 'Java'
        language id: 3, 'Scala'
    }
}
def languagesBuilder = new StreamingMarkupBuilder()
assert XmlUtil.serialize(languagesBuilder.bind(languagesXml)) == prettyXml

Continue reading →

Gradle Goodness: Task Output Annotations Create Directory Automatically

Posted on by  
Hubert Klein Ikkink

One of the great features of Gradle is incremental build support. With incremental build support a task is only executed if it is really necessary. For example if a task generates files and the files have not changed than Gradle can skip the task. This speeds up the build process, which is good. If we write our own tasks we can use annotations for properties and methods to make them behave correctly for incremental build support. The @OutputDirectory annotation for example can be used for a property or method that defines a directory that is used by the task to put files in. The nice thing is that once we have designated such a directory as the output directory we don't have to write code to create the directory if it doesn't exist. Gradle will automatically create the directory if it doesn't exist yet. If we use the @OutputFile or @OutputFiles annotation the directory part of the file name is created if it doesn't exist.

In the following example build file we create a new task SplitXmlTask with the property destinationDir and we apply the @OutputDirectory annotation. If the directory doesn't exist Gradle will create it when we execute the task.

Continue reading →

shadow-left