在 Swift 中对我自己的 ViewController 进行单元测试时使用未声明的类型“ViewController"? [英] Use of undeclared type 'ViewController' when unit testing my own ViewController in Swift?

查看:14
本文介绍了在 Swift 中对我自己的 ViewController 进行单元测试时使用未声明的类型“ViewController"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试用 Swift 编写测试用例来测试我的 ViewController.但是,当我尝试在 XCTestCase 中实例化我自己的 ViewController 时,我得到 "Use of undeclared type 'ViewController' ".(ViewController 是我自己的 UIViewController 类的名字)

I have been trying to write test cases in Swift to test my ViewController. However, when I try to instantiate my own ViewController in a XCTestCase I get "Use of undeclared type 'ViewController' ". (ViewController is the name of my own UIViewController class)

有没有其他人遇到过这个问题?我正在使用 Xcode 6 beta 5

Has anyone else faced this issue before? I am using Xcode 6 beta 5

推荐答案

Swift 1

如果你没有使用框架,你也应该添加 ViewController.swift 文件的目标成员作为你的测试目标.选择类文件添加到目标,如图所示:

Swift 1

You should add ViewController.swift file's target membership also as your test target also if you are not using framework. Select class file add to target as shown in image:

如果您的 ViewController 在一个框架内:ViewController 类在不同的目标中并且您没有声明具有公共访问级别的类.默认情况下,类是内部的(可在目标内访问).如果您想访问它,请将其声明为公共并将方法或属性设为公共,即

If you are ViewController is within a framework : ViewController class is in different target and You are not declaring class with public access level. By default Classes are internal (Accessible within a target). Declare it as public and also make methods or properties as public if you want to access it i.e

public class ViewController: UIViewController {

    public var content: String!

    override public func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override public func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

Swift 2 更新

在您的测试目标中,只需使用 @testable 关键字导入您要测试的模块:

Swift 2 Update

In your test target, just import the module you want to test using the @testable keyword:

@testable import moduleToTest

您现在可以访问测试目标中的 publicinternal 符号.

You can now access public and internal symbols in your test target.

swift 2 Xcode 7 单元测试

这篇关于在 Swift 中对我自己的 ViewController 进行单元测试时使用未声明的类型“ViewController"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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