我是OCMock的初学者,我需要验证是否从另一个类调用了一个方法。以下是我的代码。
//Creating the OCMockObject
id mockProductRequest = [OCMockObject mockForClass:[ProductRequest class]];
[[mockProductRequest expect] testProductRequest];
//Creating the object where the mock object will be invoked
ProductService *actualService = [[ProductService alloc] init];
[actualService testProductService];
[mockProductRequest verify];
-(void)testProductService{
//Method where the mock object's method is invoked
ProductRequest *request = [[ProductRequest alloc] init];
[request testProductRequest];
}
我好像总是收到一个没有调用异常的方法。请帮我弄清楚我在这里做错了什么。
答案 0 :(得分:3)
您必须替换真实ProductService
内的实际请求。例如,您可以通过使请求成为ProductService
的属性来实现此目的:
@interface ProductService
@property (strong) ProductRequest *request
然后将真实的ProductRequest与像这样的模拟者交换
- (void)testProductService {
id mockProductRequest = [OCMockObject mockForClass:[ProductRequest class]];
[[mockProductRequest expect] testProductRequest];
ProductService *actualService = [[ProductService alloc] init];
actualService.request = mockProductReqeust;
// call some method on actualService which invokes the request
[request testProductRequest];
}
答案 1 :(得分:2)
Mock Objects的目标是替换您想要测试的对象。但是在你的代码中,你将消息testProductRequest发送到一个真正的ProductRequest而不是你的MockObject!