lapots
lapots

Reputation: 13415

unit testing for java class using groovy

For this code snippet

@Component
public class StorageResource {

        @Autowired
        private Storage storage;

        public String addItem(StorageItem item) {
            WrappedStorageItem wsi = new WrappedStorageItem(item);
            storage.add(wsi);
            return wsi.getId();
        }

}

the unit test looks something like this

@Test
void testCase() {
    StorageResource storageResource = new StorageResource();
    Storage storageMock = createMock(Storage.class);
    Whitebox.setInternalState(storageResource, Storage.class, storage);

    StorageItem item = new StorageItem();
    WrappedStorageItem wos = new WrappedStorageItem(item);

    expectNew(WrappedStorageItem.class, item).andReturn(wos);
    storageMock.add(wos);
    expectLastCall();
    replayAll();
    storageResource.addItem(item);
    verifyAll();
}

But how will the test look like if I use groovy?

Will it be less verbose?

Upvotes: 1

Views: 424

Answers (1)

ataylor
ataylor

Reputation: 66109

Groovy can make tests much less verbose. How much depends on how your code is structured and what testing libraries and frameworks you are using.

As an example, Groovy provides excellent support for object mocking, which could be used to write your test like this:

def mock = new MockFor(Storage)
mock.demand.add { item -> assert item instanceof WrappedStorageItem }
mock.use {
    StorageResource storageResource = new StorageResource(storage: new Storage())
    storageResource.addItem(new StorageItem())
    // verify is implicit
}

In addition, setting up test fixtures is generally much less verbose in Groovy, as you can take advantage of the built-in list and map syntax (e.g. [1, 2, 3] instead of x = new ArrayList(); x.add(1); x.add(2); x.add(3)).

Upvotes: 2

Related Questions