单元测试类中的私有方法? [英] Unit testing private methods from a category?

查看:438
本文介绍了单元测试类中的私有方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 NSString 类包含一个私人辅助方法的类。
如果我可以在我的单元测试中使用这个方法将会很方便。
但是我有困难暴露它。
当我在NSString上创建一个类扩展并在这里声明方法时,该方法在单元测试中不可见。如果我在一个单独的头文件中创建类扩展,或者作为单元测试.m文件的一部分,这并不重要。

I have a category on NSString class that contains a private helper method. It would be handy if I could use this method in my unit test. However I have difficulties to expose it. When I create a class extension on NSString and declare the method here, the method is not visible in unit test. And it doesn't matter if I create the class extension in a separate header file, or as a part of unit test .m file.

看起来我在这里缺少一些东西。

It looks like I am missing something here.

任何帮助人吗?

推荐答案

通用单元测试指南会告诉你不要尝试和测试你的私有方法。只通过您的公共接口测试。私有方法只是一个实现细节,可以随时改变,当你重构。

Common unit testing guidance would tell you not to try and test your private methods. Only test via your public interfaces. Private methods are simply an implementation detail that could change at any time, when you refactor. Your public interfaces should be pretty stable, and will exercise your private methods.

但是,如果你仍然想测试你的私有类别方法,下面的代码适用于我。

However, if you still want to test your private category methods, the following works for me...

首先,您的类别:

@interface UIImage (Example)    
@end


b $ b

UIImage + Example.m



UIImage+Example.m

@implementation UIImage (Example)

+ (NSString *)examplePrivateMethod
{
    return @"Testing";
}

@end



MyExampleTests.m



MyExampleTests.m

#import <XCTest/XCTest.h>
#import "UIImage+Example.h"

@interface UIImage (Example_Test)
+ (NSString *)examplePrivateMethod;
@end

@interface MyExampleTests : XCTestCase
@end

@implementation MyExampleTests

- (void)testExample
{
    XCTAssertEqualObjects(@"Test", [UIImage examplePrivateMethod], @"Test should be test");
}

@end

基本上,重新声明您的私有方法在你的测试中的新类别。但是,如上所述,这是暴露私有方法只是为了测试的目的,并将您的测试与您的实现耦合。

Essentially, redeclare your private method in a new category in your test. However, as mentioned above this is exposing private methods just for the purpose of testing, and coupling your tests to your implementation.

这篇关于单元测试类中的私有方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆