简体   繁体   English

使用groovy对Java类进行单元测试

[英]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 ? 但是如果使用groovy ,测试会如何?

Will it be less verbose? 会不会那么冗长?

Groovy can make tests much less verbose. Groovy可以使测试的详细程度降低得多。 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: 例如,Groovy为对象模拟提供了出色的支持,可用于编写如下测试:

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) ). 此外,在Groovy中设置测试装置通常不会那么冗长,因为您可以利用内置列表和映射语法(例如[1, 2, 3]代替x = new ArrayList(); x.add(1); x.add(2); x.add(3) )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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