1

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?

4
  • In this situation it is hard to tell but most likely Groovy will make it a little less verbose but not a great deal. The biggest bang for your buck would be considering trying Spock which truly takes advantage of Groovy for making your tests (or Specifications) easier to read and maintain. Commented Feb 1, 2016 at 15:40
  • 1
    I can write a Spock example if your interested. Commented Feb 1, 2016 at 15:44
  • @ToddWCrone, yes please. It would be interesting. Commented Feb 2, 2016 at 6:23
  • Give me a couple days to get to it. In the meantime, here is a fairly simple example of using Spock to solve a problem. github.com/twcrone/stock-problem/blob/master/src/test/groovy/… Commented Feb 3, 2016 at 22:05

1 Answer 1

2

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)).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.