Posts by Albert van Veen

Geb Gems: Handling AJAX requests

Posted on by  
Albert van Veen

One of the biggest struggles while testing web applications that use AJAX is dealing with the timing issues caused by asynchronous nature of the request. A common solution is using timeouts to wait for the AJAX call to be completed. This could cause lots of timing issues. Using Geb there is a better way to determine that the AJAX call and its callback has been completed.

In this blog post we will test the W3Schools website which has a button on it which executes an AJAX request: http://www.w3schools.com/ajax/ajax_example.asp

Continue reading →

Geb Gems: Using Pages and Modules

Posted on by  
Albert van Veen

In the previous blog post about Geb, we have been introduced to the Geb Framework. In this blogpost we will be introduced to Pages and Modules. A Page represents a specific page from a web application. A module represent a part of the page; for example a sign-up form, a menu bar or contact form. Pages and Modules are very useful since they are very easy to reuse and therefore useful to create more advanced UI tests. In this blogpost we are going to use Pages and Modules to test the contact form of the JDriven website. We will verify that a success message will appear if we submit a valid form. Pages have a url attribute which represent the address to the page. To get the complete url, Geb requires a baseUrl which we can define in the GebConfig.groovy

baseUrl = "http://www.jdriven.com/"

Continue reading →

Geb Gems: Running Geb Spock tests with Maven

Posted on by  
Albert van Veen

Geb is framework which makes it easy to create functional tests for your application. Since you can use Groovy, Spock and the elegance of the JQuery selector, you can setup solid functional test very easy. In this blogpost we will make a simple test which will test a functional part of the JDriven website. We will start our test with configuring the Maven POM file. We need to add the following dependencies.

         <dependencies><dependency>
            <groupId>org.codehaus.groovy</groupId>
            <artifactId>groovy-all</artifactId>
            <version>2.4.3</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.spockframework</groupId>
            <artifactId>spock-core</artifactId>
            <version>1.0-groovy-2.4</version>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.codehaus.groovy</groupId>
                    <artifactId>groovy-all</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.gebish</groupId>
            <artifactId>geb-spock</artifactId>
            <version>0.10.0</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-firefox-driver</artifactId>
            <version>2.45.0</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

Continue reading →

Grails: Preventing naming collisions

Posted on by  
Albert van Veen

Since version 2.2 Grails, has better support for managing namespace configuration. This helps to prevent common namespace problems. For example most applications which have security functionality, have for example a UserDetailService which can conflict when you have the Grails SpringSecurity plugin installed. Grails version 2.2. and later comes with four useful techniques to make sure the right class is used

If Grails does not find an existing service with a similar name, Grails will automatically generate an alias for you service with the name of the plugin prefix. For example when you have a plugin called UserUtilities and a service called UserDetailService, you can use UserUtilitiesUserDetailService for dependency injection which will not conflict with the SpringSecurity UserDetailService

Continue reading →

Groovy @CompileStatic vs. Grails new @GrailsCompileStatic

Posted on by  
Albert van Veen

Grails is built on Groovy which is known as a dynamic language. The dynamic nature of Groovy offers a lot of powerful features but also defers the detection of errors from compile time to runtime. To shorten the feedback cycle for your code Groovy has a handy annotation which will make sure that your classes is are statically compiled. This will give you fast feedback for a lot of mistakes and you also will benefit from the increased performance offered by the static complication. Unfortunately in Grails this annotation prevents you from using the very useful dynamic GORM methods like list(), get() and the dynamic finder methods. Groovy does not recognize these Grails methods during compile time; see the example below.

@CompileStatic
class BookController(){

     def save(){
       //This will successfully compile
    }

    def get(){
       Book.findByName(params.name)
       //this will throw a compile error since the findByName method is not known
       //at compile time
    }

    @CompileStatic(TypeCheckingMode.SKIP)
    def delete(){
       //by setting the TypeCheckinMode, this method will be skipped
    }
}

Continue reading →

Spock: Using ConfineMetaClassChanges when using MetaClass mocking

Posted on by  
Albert van Veen

One of the handy features of Groovy is to change the behavior of classes using MOP (Meta-Object Protocol). We change the metaClass property of a class to alter an implementation. You can for example override a static method of a class. See the example below:

class UserSpec extends Specification {

    def “test user”() {
        given:
        // we can mock static methods...
        User.metaClass.static.findByName = { name ->
            new User(name: ‘Albert’) }
        when:
        User user = User.findByName(‘Albert’)

        then:
        user.name == ‘Albert’

        when:
        // .. but also non-static methods
        user.metaClass.getName = { return ‘Dries’ }

        then:
        user.name == ‘Dries’
    }

}

Continue reading →

Grails Generate Asynchronous Controller

Posted on by  
Albert van Veen

Since version 2.3, Grails supports asynchronous parallel programming to support modern multiple core hardware. Therefore a new Grails command is added to generate asynchronous controllers for domain classes. The generated controller contains CRUD actions for a given domain class. In the example below, we will generate a default asynchronous implementation of a Grails controller. First we create a domain object:

$ grails create-domain-class grails.data.Movie

Continue reading →

Grails REST: Generate RestfulController

Posted on by  
Albert van Veen

Since version 2.3 Grails has excellent support for creating REST APIs. This new support comes with some new console commands. Besides the well known generate-controller command, Grails now comes with a new command which let you generate restful controllers for a given domain class. In the following example, we will create a restful controller using the new generate-restful-controller command. First we create a domain object

$ grails create-domain-class grails.data.Movie

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 →

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 →

JAXB class generation using Maven

Posted on by  
Albert van Veen

There is a useful maven plugin to generate all our JAXB classes for us. This plugin can be executed during the generate-sources phase of our maven build. It can be very useful, especially in the first stages of our project when the design of our XSD may change frequently. We can just add the plugin configuration to the pom.xml of our project.

<plugin>
    <groupId>org.jvnet.jaxb2.maven2</groupId>
    <artifactId>maven-jaxb2-plugin</artifactId>

    <configuration>
        <extension>true</extension>
        <args>
            <arg>-Xfluent-api</arg>
        </args>
        <plugins>
            <plugin>
                <groupId>net.java.dev.jaxb2-commons</groupId>
                <artifactId>jaxb-fluent-api</artifactId>
                <version>2.1.8</version>
            </plugin>
        </plugins>
        <bindingDirectory>src/main/resources/</bindingDirectory>
    </configuration>
    <executions>
        <execution>
            <goals>
                <goal>generate</goal>
            </goals>
        </execution>
    </executions>
</plugin>

Continue reading →

shadow-left