Flex单元测试:asmock模拟对象

在单元测试中,经常有模拟对象(mock)的需求,而在FlexUnit里,可以通过asmock来创建mock对象。

首先,需要在单元测试类中定义将被mock的类,同时定义mock repository变量:

[Rule]
public var includeMocks:IncludeMocksRule = new IncludeMocksRule([ToMockClass]);  
private var _mockRepository:MockRepository = null;  
private var _toMockClassInstance:ToMockClass = null;  

然后,在setUp()函数中定义mock repository对象,并mock出假的ToMockClass实例,同时指定该假实例的行为:

[Before]
public function setUp():void {  
    _mockRepository = new MockRepository();
    _toMockClassInstance = _mockRepository.createStub(ToMockClass) as ToMockClass;
    SetupResult.forCall(_toMockClassInstance.testFunc(null, null)).ignoreArguments().dispatchEvent(new Event("MockReturnedEvent"));
    SetupResult.forCall(_toMockClassInstance.testFunc2(null)).ignoreArguments().returnValue(42);
    _mockRepository.replay(_toMockClassInstance);
}

之后,该mock实例就可以被用于写Test Case了:

[Test]
public function testCase1():void {  
    var x:TestClass = new TestClass(_toMockClassInstance);
    x.doSomething(); //_toMockClassInstance's testFunc() or testFunc2() method will be invoked.
    assertThat...
}

最后,只需对mock相关的实例在tearDown()函数中清零即可:

[After]
public function tearDown():void {  
    _toMockClassInstance = null;
    _mockRepository = null;
}