Stephen’s Statements A little bit of everything from Stephen Duncan Jr, a Software Developer in Portland, Oregon

Sunday, September 17, 2006

EasyMock-PropertyUtils Example

Here’s the promised example of how to use my EasyMock-PropertyUtils library. It’s a TestNG test class with two test methods. The first, testSayHelloTo() uses the single-property matcher test. The second, testSay() uses the multiple-property matcher test by supplying a Map of property names to property values. If you haven’t used EasyMock before, this should also serve as an example of how EasyMock can allow you to unit test in isolation a method that interacts with another class. Check out the EasyMock Documentation for more information.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package test;

import static com.stephenduncanjr.easymock.EasyMockPropertyUtils.propertiesEq;
import static com.stephenduncanjr.easymock.EasyMockPropertyUtils.propertyEq;
import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.replay;
import static org.easymock.EasyMock.verify;

import java.util.HashMap;
import java.util.Map;

import org.testng.annotations.Test;

/**
 * Test the Service class.
 */
public class ServiceTest
{
    /**
     * Test the sayHelloTo method.
     */
    @Test
    public void testSayHelloTo()
    {
        String address = "someone@example.com";
        MessagingService messagingService = createMock(MessagingService.class);
        messagingService.sendMessage(propertyEq(Message.class, "address", address));
        replay(messagingService);

        Service service = new Service();
        service.setMessagingService(messagingService);
        service.sayHelloTo(address);

        verify(messagingService);
    }

    /**
     * Test the say method.
     */
    @Test
    public void testSay()
    {
        String address = "someone@example.com";
        String text = "some text";

        Map<String, Object> properties = new HashMap<String, Object>();
        properties.put("address", address);
        properties.put("message", text);

        MessagingService messagingService = createMock(MessagingService.class);
        messagingService.sendMessage(propertiesEq(Message.class, properties));
        replay(messagingService);

        Service service = new Service();
        service.setMessagingService(messagingService);
        service.say(address, text);

        verify(messagingService);
    }
}