Monthly Archives: August 2010

In Pursuit of the Cross-Functional Team

During agile transition, it is common that large organizations take the books and advices word by word. In scrum, it is advised to have cross-functional teams. This advice is unfortunately sometimes interpreted in the wrong way. For some people, cross-functional team means that everyone on the team shares the same technical and business knowledge about the tasks that the team is supposed to work on. This kind of transition is not only very very expensive – time and money -, but scares the management. I joined an organization, where, unfortunately, the goal was to create teams using this interpretation, and after a couple of months I can tell that it did not worth it. We could have used the time we spent on the cross-functional build-up on delivering more features of the product.

Transition is usually done in several steps and on different layers of a large organization. Usually, first developers do it, then testers, and management at the end. For management, a team where everybody is an expert is very scary. They don’t get the point of it – because of the false interpretation -, they do not understand why train experts, why should everybody be an expert, when the only thing they want to do is deliver features to the customer. These doubts make them confused about the whole transition, and when a manager has doubts, he’ll turn to the old, “this has worked before” ideas, and usually the organization is back at square one.

I prefer the cross-functional team definition from stackoverflow and wikipedia: A cross-functional team is a group of people with different functional expertise working toward a common goal.

I believe that teams can master this definition and get better and faster at what they are doing, but it shouldn’t be the first thing they implement. Start with engineering practises (like XP) and scrum team set-up instead. If the team is getting to understand the main scrum principles, they can start working on being cross-functional. This is very difficult, hence I was thinking about a way to do it. Retrospectives are a great way to find goals for a team, why not set a goal like being more cross-functional?

During a retrospective, it is usually not known on exactly which user stories the team will work during the next sprint(s) (retrospectives are before planning meetings), but the release plan is kind of known. Take a brief description of user stories from the release plan to the retrospective and ask the participants to have a look at them. As a next step, take a bus factor of 1. Ask around whether the team would be able to work on the user stories if any of the members were absent during the next sprints. Let’s assume that the team consists of seven people, meaning that they shall check seven possibilities. If they find at least one case when they won’t be able to deliver any user stories, that means that the team found a knowledge bottleneck. I advise to stop here at the first time, and find a goal to share that knowledge; not among everyone, try to reach bus factor 2. A solution can be pairing up with the colleague or team member who has the knowledge, or asking him to keep dojos about his knowledge.

The goal is not to train backup persons for certain areas, but to share information in order to go better and faster: the more people are familiar with a certain area, the better the team performs, but there is no need for them to be on the same level. The team can go on with the practise above until they can survive a sprint when 45% of the current team is not available. In the example the team shall continue the retrospective game until they reach the bus factor 3.

This game is also helpful when the team changes. By default, the knowledge of the new members is not known by the old members, but with this easy game, new members can expose their knowledge to the team. It may happen that they have the knowledge for working on user stories in the upcoming sprints. In this case the team saves valuable time: they can work on features instead of trainings. On the other hand, if the necessary knowledge is not available, the game starting with bus factor 1 can help to build up the overall team knowledge from scratch.

VN:F [1.9.17_1161]
Rating: 7.0/10 (1 vote cast)

Agile Corner

I’m working in a quite large organization (several teams with different goals and purposes), and realized that it is very hard to distribute ideas among colleagues, and it is even harder to follow their agile development. I participated in the open space sessions at xp2010, and got an idea. Maybe we could do something similar for helping the situation.

We are going to keep agile corner sessions where colleagues can show up and discuss strictly agile related topics. We collect the topics we would like to talk about. After the list of topics is available, we’ll vote which topics to discuss. Like in open space, people can join or leave at any time. If we find something useful for a team, we’ll put it down into the agile backlog so that we can track it, and discuss its progress during the next session.

An agile backlog is similar to a backlog in scrum, but it contains user stories which tell an agile thing to implement in the team. For example, once we had a user story for introducing acceptance test driven development in bug fixing, in other teams, they had a user story to try out new games during retrospective.

It is very important to track these improvements, because, based on my experience, a change survives a couple of days, maybe weeks, but after that the team gets back to is previous way of doing things. If we have a list of change items, we can revisit the list and check on that particular item.

VN:F [1.9.17_1161]
Rating: 0.0/10 (0 votes cast)

jMock versus Mockito

I’ve been using jMock for more than a year now, but recently I came across mockito. In this post, I’ll show the difference between jMock and mockito – without judging which one is better – using the basic features I’ve been using the most often from jMock. I admit that there are more features than presented in this post, but for starters, I find these enough.

The versions under comparison:

The Test Object

For this demonstration, I’m using a very fictional, but simple code example which fits the purpose of comparison.

The skeleton of the main class which is going to be tested:

public class PosTerminal {
 
	private static final String SHOP_ACCOUNT_NUMBER = "00000000-00000000";
	private final ReceiptPrinter receiptPrinter;
	private final BankConnection bankConnection;
 
	public PosTerminal(BankConnection bankConnection,
                           ReceiptPrinter receiptPrinter) {
		this.bankConnection = bankConnection;
		this.receiptPrinter = receiptPrinter;
	}
 
	public boolean buyWithCard(int amountOfMoney, String cardNumber) {
	}
}

The skeleton of the first injected class:

public class BankConnection {
 
	public Account getAccountByCardNumber(String cardNumber) {
		return null;
	}
 
	public Account getAccountByAccountNumber(String accountNumber) {
		return null;
	}
}

The skeleton of the second injected class:

public class ReceiptPrinter {
	public void print(String string) {
	}
}

And the interface for accounts:

public interface Account {
        boolean withdraw(int amountOfMoney, String destinationAccountNumber);
        boolean enter(int amountOfMoney, String sourceAccountNumber);
        void rollback();
        void commit();
}

Creating Mocks

jMock

import org.jmock.Mockery;
import org.junit.Test;
 
public class PosTerminalTest {
    @Test
    public void shouldPrintSuccessfulWithdrawal() {
        Mockery context = new Mockery();
 
        BankConnection bankConnection = context.mock(BankConnection.class);
        ReceiptPrinter receiptPrinter = context.mock(ReceiptPrinter.class);
        // the test case continues...
    }
}

mockito

import static org.mockito.Mockito.mock;
import org.junit.Test;
 
public class PosTerminalTest {
    @Test
    public void shouldPrintSuccessfulWithdrawal() {
        BankConnection bankConnection = mock(BankConnection.class);
        ReceiptPrinter receiptPrinter = mock(ReceiptPrinter.class);
        // the test case continues...
   }
}

There is no significant difference here. jMock uses a context for handling mocks, while mockito solves it with statically imported methods.

Mocking Classes

If you compile and execute the examples above, the following exception is raised when the jMock test case is executed:

java.lang.IllegalArgumentException: com.zsoltfabok.dojo.mocks.BankConnection is not an interface

jMock is designed to mock interfaces, not classes. It forces the developer to use interfaces, which is a good programming practice, but sometimes it is an overhead. Imagine that you are working on a legacy code. There is no way to extract interfaces for every single class just to satisfy a mocking framework. Fortunately, you can set jMock so that it can mock classes:

        // the same as before ...
        Mockery context = new Mockery() {{
            setImposteriser(ClassImposteriser.INSTANCE);
        }};
        // the same as before ...

There is no need for such setting in the mockito based test case.

Two Of The Same Kind of Mocks

During testing the PosTerminal class, we need to fetch two Accounts from the BankConnection. One for the card owner (customer) and one for the shop. They will be mocks, too:

jMock

        // the same as before ...
        Account customerAccount = context.mock(Account.class);
        Account shopAccount = context.mock(Account.class);
        // the same as before ...

mockito

        // the same as before ...
        Account customerAccount = mock(Account.class);
        Account shopAccount = mock(Account.class);
        // the same as before ...

No difference here at first sight. After executing the jMock test case, the following exception is raised:

java.lang.IllegalArgumentException: a mock with name account already exists

Internally, jMock uses name references for handling mocks, and if no name is specified, the name will be the type of the mock. In the example above, we have two Accounts with the same name. The problem can be solved easily:

        // the same as before ...
        Account customerAccount = context.mock(Account.class, "customer account");
        Account shopAccount = context.mock(Account.class, "shop account");
        // the same as before ...

Annotation

Based on the mockito and jMock documentation it is possible to setup mocks with annotations, which is excellent, because with this approach, I can make the test case much simpler.

jMock

Although the current stable jMock documentation describes the @Mock annotation, I was unable to find it in the framework.

mockito

import org.mockito.Mock;
// Other import statements ...
 
@RunWith(MockitoJUnitRunner.class)
public class PosTerminalTest {
    @Mock
    private BankConnection bankConnection;
    @Mock
    private ReceiptPrinter receiptPrinter;
    @Mock
    private Account customerAccount;
    @Mock
    private Account shopAccount;
 
    @Test
    public void shouldPrintSuccessfulWithdrawal() {
    }
}

Note that in order to make it work, you need a @RunWith annotation.

Call Verification and Return Value Handling

This is the good part; how our class communicates with the injected classes. The verification is quite simple: check whether or not a method of the mock is called. The other thing is how our class can handle the return value of a method of a mock.

jMock

    @Test
    public void shouldPrintSuccessfulWithdrawal() {
        PosTerminal posTerminal = new PosTerminal(bankConnection, receiptPrinter);
 
        context.checking(new Expectations() {{
            oneOf(bankConnection).getAccountByCardNumber("1000-0000-0001-0003");
            will(returnValue(customerAccount));
 
            // Other oneOf() will() statements ...
 
            oneOf(receiptPrinter).print("Successful withdrawal");
        }});
 
        posTerminal.buyWithCard(100, "1000-0000-0001-0003");
    }

mockito

    @Test
    public void shouldPrintSuccessfulWithdrawal() {
        PosTerminal posTerminal = new PosTerminal(bankConnection, receiptPrinter);
 
        when(bankConnection.getAccountByCardNumber("1000-0000-0001-0003"))
            .thenReturn(customerAccount);
        // Other when(...).thenReturn(...) calls ...
 
        posTerminal.buyWithCard(100, "1000-0000-0001-0003");
 
        verify(receiptPrinter).print("Successful withdrawal");
    }

The order in which the methods are called is important. In case of jMock, the Expectations shall come before the method call, and in case of mockito the verify() always afterwards. There is no significant difference between jMock and mockito in this case, besides readability. The verify() method call clearly states that the we are just checking if a method is called. This clear difference makes the code more readable for me. Another readability thing is that for me, the inner class Expectations is less readable. If the mocks are not fields, then, because of the inner class, I have to make the mocks final.

Argument Matchers

Sometimes one or more arguments are not relevant when a method of a mock object is called.

jMock

        context.checking(new Expectations() {{
            // Other oneOf() will() statements ...
 
            oneOf(customerAccount).withdraw(with(any(Integer.class)),
                    with(any(String.class)));
            will(returnValue(true));
 
            oneOf(shopAccount).enter(with(100), with(any(String.class)));
            will(returnValue(true));
 
           // Other oneOf() will() statements ...
        }});

mockito

import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
// Other parts of the code ...
    @Test
    public void shouldPrintSuccessfulWithdrawal() {
       // Other when(...).thenReturn(...) calls ...
 
        when(customerAccount.withdraw(anyInt(), anyString())).thenReturn(true);
        when(shopAccount.enter(eq(100), anyString())).thenReturn(true);
 
        // Other when(...).thenReturn(...)  and verify(...) calls ...
    }

The are no differences here, but I find the mockito version more readable. One additional thing is that neither of the frameworks support mixing the matchers with exact matches, for example:

jMock

Mind the missing with() call:

        context.checking(new Expectations() {{
            // Other oneOf() will() statements ...
 
            oneOf(shopAccount).enter(100, with(any(String.class)));
            will(returnValue(true));
 
           // Other oneOf() will() statements ...
        }});

The following exception will be raised during execution:

java.lang.IllegalArgumentException: not all parameters were given explicit matchers: either all parameters must be specified by matchers or all must be specified by values, you cannot mix matchers and values

mockito

Mind the missing eq() call:

       // Other when(...).thenReturn(...) calls ...
 
        when(shopAccount.enter(100, anyString())).thenReturn(true);
 
        // Other when(...).thenReturn(...)  and verify(...) calls ...

The following exception will be raised during execution:

org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Invalid use of argument matchers!
2 matchers expected, 1 recorded.
This exception may occur if matchers are combined with raw values:
//incorrect:
someMethod(anyObject(), “raw String”);
When using matchers, all arguments have to be provided by matchers.
For example:
//correct:
someMethod(anyObject(), eq(“String by matcher”));
org.mockito.exceptions.misusing.InvalidUseOfMatchersException: Invalid use of argument matchers!2 matchers expected, 1 recorded.This exception may occur if matchers are combined with raw values:    //incorrect:    someMethod(anyObject(), “raw String”);When using matchers, all arguments have to be provided by matchers.For example:    //correct:    someMethod(anyObject(), eq(“String by matcher”));

The output of mockito provides a bit more information.

Number of Invocations

Sometimes the number of invocations of a certain method is important. The approaches of jMock and mockito are quite the same, except that the number of invocations is used with the verify() method in mockito.

jMock

        context.checking(new Expectations() {{
           // Other oneOf() will() statements ...
 
            exactly(1).of(receiptPrinter).print(with(any(String.class)));
        }});

or

        context.checking(new Expectations() {{
           // Other oneOf() will() statements ...
 
            atLeast(1).of(receiptPrinter).print(with(any(String.class)));
        }});

or

        context.checking(new Expectations() {{
           // Other oneOf() will() statements ...
 
            never(receiptPrinter).print(with(any(String.class)));
        }});

mockito

       // Other when(...).thenReturn(...) calls ...
 
        verify(receiptPrinter, times(1)).print(anyString());
 
        // Other verify() calls ...

or

       // Other when(...).thenReturn(...) calls ...
 
        verify(receiptPrinter, atLeast(1)).print(anyString());
 
        // Other verify() calls ...

or

       // Other when(...).thenReturn(...) calls ...
 
        verify(receiptPrinter, never()).print(anyString());
 
        // Other verify() calls ...

There are plenty of other possibilities. jMock has allowing() and ignoring() options, which are not available in mockito. On the other hand, mockito has an only() method which makes the code more readable. In jMock, if an unexpected method call is made, a RuntimeException is thrown. In mockito this feature is not available. There is an issue for it with number 162.

Consecutive Calls

jMock

        context.checking(new Expectations() {{
            // Other oneOf() will() statements ...
 
            oneOf(shopAccount).enter(with(100), with(any(String.class)));
            will(onConsecutiveCalls(returnValue(true), returnValue(false),
                 returnValue(false)));
        }});

mockito

        // Other when(...).thenReturn(...) calls ...
        when(shopAccount.enter(eq(100), anyString())).thenReturn(true, false, false);

No difference, but I find mockito more readable.

Verify Call Order

jMock

    @Test
    public void shouldPrintSuccessfulWithdrawal() {
        PosTerminal posTerminal = new PosTerminal(bankConnection, receiptPrinter);
 
        final Sequence sequence = context.sequence("account order");
        context.checking(new Expectations() {{
            // Other oneOf() will() statements ...
 
            oneOf(customerAccount).withdraw(with(any(Integer.class)),
                    with(any(String.class)));
            will(returnValue(true));
            inSequence(sequence);
 
            atLeast(1).of(shopAccount).enter(with(100), with(any(String.class)));
            will(returnValue(true));
            inSequence(sequence);
        }});
 
        posTerminal.buyWithCard(100, "1000-0000-0001-0003");
    }

mockito

    @Test
    public void shouldPrintSuccessfulWithdrawal() {
        PosTerminal posTerminal = new PosTerminal(bankConnection, receiptPrinter);
 
        posTerminal.buyWithCard(100, "1000-0000-0001-0003");
 
        InOrder inOrder = Mockito.inOrder(customerAccount, shopAccount);
        inOrder.verify(customerAccount).withdraw(anyInt(), anyString());
        inOrder.verify(shopAccount).enter(anyInt(), anyString());
 
        verify(receiptPrinter).print(anyString());
    }

One significant difference here: in case of mockito the involved mocks need to be injected when creating the InOrder (Sequence equivalent) object.

Exception Handling

jMock

        context.checking(new Expectations() {{
            oneOf(bankConnection).getAccountByCardNumber("1000-0000-0001-0003");
            will(throwException(new RuntimeException()));
         }});

mockito

        when(bankConnection.getAccountByCardNumber("1000-0000-0001-0003"))
        	.thenThrow(new RuntimeException());

No difference, other than readability.

Setup

In order to make the examples compile and run I had to add the following external libraries.

jMock

  • jmock-2.5.1.jar
  • jmock-junit4-2.5.1.jar
  • hamcrest-core-1.1.jar
  • hamcrest-library-1.1.jar
  • jmock-legacy-2.5.1.jar
  • cglib-2.1_3-src.jar
  • cglib-nodep-2.1_3.jar
  • objenesis-1.0.jar

mockito

  • mockito-all-1.8.5.jar

Some of the jMock libraries were added after I tried to run my test cases and it took me quite some time to find out the right build path. With mockito, I just had to add one simple jar file.

Conclusion

jMock and mockito are both very well documented with examples and good practical hints. However, based on the examples above I find the test cases more readable with mockito. In my next project I’m definitely going to work with mockito. One good advice: if you make the same decision, do not mix jMock and mockito in your test code. It will make your code unreadable, and additionally it might not even work: it would be hard to execute a mockito mock related code in a jMock TestRunner (mind the @RunWith annotations).

VN:F [1.9.17_1161]
Rating: 10.0/10 (4 votes cast)