在Grails中模拟构造函数

时间:2009-07-31 23:39:47

标签: unit-testing grails mocking

我刚接触Grails测试,所以我不确定我是否采取了正确的方法。我正在尝试对具有另一个类的实例(称为Bar)作为属性的服务(称为FooService)进行单元测试。基本上是这样的:

class FooService {
 Bar bar

 void afterPropertiesSet() {
  bar = new Bar()
 }
}

所以,我正在尝试测试afterPropertiesSet方法,据我所知,单元测试的正确做法是模拟外部类。那么,在FooServiceTests中如何扩展GrailsUnitTestCase,我是否可以模拟Bar构造函数?

由于

3 个答案:

答案 0 :(得分:1)

回答太晚了,但如果将来有人想要的话。

            def barObj
            def barCtrl= mockFor(Bar )
            Bar.metaClass.constructor = { ->
                barObj=[:]
                return barObj
            }

 when:
        service.afterPropertiesSet()

        then:
        assert barObj == //check the properties

答案 1 :(得分:0)

你没有。

EasyMock依赖于代理,这意味着一个接口。除非Bar可以作为接口,否则它不是代理的候选者。

你已经模拟了类似DAO或其他外部依赖的东西,你已经过单元测试,以防止你的FooServiceTest成为集成测试,但是Bar?否。

“......单元测试的正确做法是模拟外部类......” - 我认为这是不正确的。对每个对象进行模拟都会让这个想法过得太远。

答案 2 :(得分:0)

如果您确实需要或想要模拟Bar构造函数,则可以。

使用JMockit,您可以编写(在下面的Java中,请参阅here关于在Groovy中使用它):


import org.junit.*;
import org.junit.runner.*;

import mockit.*;
import mockit.integration.junit4.*;

@RunWith(JMockit.class)
public class FooServiceTest
{
    @Test
    public void afterPropertiesSet()
    {
        new Expectations()
        {
            Bar mockBar;

            {
                new Bar(); // records expectation for the Bar constructor
            }
        };

        // Will call a mocked "Bar()":
        new FooService().afterPropertiesSet();
    }
}