简体   繁体   中英

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?

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 (eg [1, 2, 3] instead of x = new ArrayList(); x.add(1); x.add(2); x.add(3) ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM