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 →
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 →
Willem Cheizoo already wrote an blog post about How to test for an exception with JUnit and this inspired me to write the same sample with Spock. In Spock we can use the thrown()
method to check for exceptions. We can use it in a then:
block of our test.
import spock.lang.*
public class JDrivenServiceSpecification extends Specification {
private JDrivenService service = new JDrivenService()
def "publishArticle throws ArticleNotFoundException() {
when:
service.publishArticle null
then:
final ArticleNotFoundException exception = thrown()
// Alternate syntax: def exception = thrown(ArticleNotFoundException)
exception.message == 'Article not found please provide an article to publish'
}
}
Continue reading →
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 →
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 →
Since Grails 2.1 we can create a Grails wrapper. The wrapper allows developer to run Grails commands in a project without installing Grails first. The wrapper concept is also available in other projects from the Groovy ecosystem like Gradle or Griffon. A wrapper is a shell script for Windows, OSX or Linux named grailsw.bat
or grailsw
and a couple of JAR files to automatically download a specific version of Grails. We can check in the shell scripts and supporting files into a version control system and make it part of the project. Developers working on the project simply check out the code and execute the shell script. If there is no Grails installation available then it will be downloaded. To create the shell scripts and supporting files someone on the project must run the wrapper command for the first time. This developer must have a valid Grails installation. The files that are generated can then be added to version control and from then one developers can use the grailsw
or grailsw.bat
shell scripts.
$ grails wrapper
| Wrapper installed successfully
$
Continue reading →
When experimenting with AngularJS features I often create a so-called Plunk on http://plnkr.co/. Although this site provides built-in templates for AngularJS, I found it useful to create my own since:
- The “1.0.x (stable)” / “1.0.2 + Jasmine” templates use old versions of AngularJS;
- “1.0.2 + Jasmine” template solely outputs Jasmine results but no AngularJS content.
Continue reading →
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
Continue reading →
We can configure Spring beans using several methods in Grails. We can for example add them to grails-app/conf/spring/resources.xml
using Spring’s XML syntax. But we can also use a more Groovy way with grails-app/conf/spring/resources.groovy
. We can use a DSL to define or configure Spring beans that we want to use in our Grails application. Grails uses BeanBuilder to parse the DSL and populate the Spring application context. To define a bean we use the following syntax beanName(BeanClass)
. If we want to set a property value for the bean we use a closure and in the closure we set the property values. Let’s first create a simple class we want to configure in the Spring application context:
// File: src/groovy/com/mrhaki/spring/Person.groovy
package com.mrhaki.spring
import groovy.transform.ToString
@ToString
class Person {
String name
Date birthDate
}
Continue reading →
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 →
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 →