我有一个用swift编写的iOS应用程序,但是根据需要,模拟测试是用Objective-c编写的(ocmock.org/swift /)。
我有一个实用程序类方法,可以从CBLD文档中构建一个CBLView(想想一个索引)(想想json)。
我可以完美地模拟(CBLDatabase)数据库并验证交互 - 完美!
但我有一个模拟方法返回另一个模拟,我也想验证与该模拟的交互。
我正在仔细盯着OCMock的精美文档:http://ocmock.org/reference/
浏览精细的stackoverflow,例如:OCMock test fails - expected method was not invoked
当我运行调试器时,似乎CBLView并没有真正像数据库一样被模拟,至少视图对象不会像OCClassMockObject
那样用数据库对象包装。
我还不清楚如何模拟一个返回另一个可以验证的模拟的方法。为什么?我该如何解决?
我的班级方法大致如下:
@objc
public class CouchUtils: NSObject, CouchUtilsProtocol {
static func getView(
database: CBLDatabase,
designDocName: String,
viewName: String
) -> CBLView? {
let designDoc = database.existingDocumentWithID("_design/" + designDocName)
...
let mapBlock = CBLView.compiler().compileMapFunction(mapSource!,
language: language!)
...
let view = database.viewNamed(viewId)
view.setMapBlock(mapBlock!, version: "1")
return view
}
}
我的OCMock测试如下:
#import <XCTest/XCTest.h>
#import <OCMock/OCMock.h>
#import <CouchbaseLite/CouchbaseLite.h>
#import "MyAppTests-Swift.h"
#import "MyApp-Swift.h"
@interface CouchUtilsTests : XCTestCase
@end
@implementation CouchUtilsTests
- (void)testGetView
{
// 1. Mock
id doc = OCMPartialMock([CBLDocument new]);
NSString *mapFunction = @"function (doc) { if (typeof doc.type !== 'undefined') \
{ emit(doc.type, {title: doc.title}); }; }";
NSDictionary *all = @{@"language": @"javascript",
@"map": mapFunction };
// niecetohave: have a reduce as well ~ in a seperate test case
NSDictionary *properties = @{@"views": @{@"types": all}};
OCMStub([doc properties]).andReturn(properties);
id mockCBLView = OCMPartialMock([CBLView new]);
OCMStub([mockCBLView createQuery]).andReturn(@"Query created");
id mockDatabase = OCMPartialMock([CBLDatabase new]);
OCMStub([mockDatabase existingDocumentWithID: @"_design/all"]).andReturn(doc);
OCMStub([mockDatabase viewNamed: @"all/types"]).andReturn(mockCBLView);
// 2. Run code under test
id view = [CouchUtils getView: mockDatabase
designDocName: @"all"
viewName: @"types"];
// 3. Verify expectations
// fails
OCMVerify([mockCBLView setMapBlock: [OCMArg any] version: @"1"]);
// works
OCMVerifyAll(mockDatabase);
XCTAssertEqualObjects(@"Query created",
[view createQuery],
@"Must get a CBLView that can be queried");
}
@end