unit-testing - Swift - 测试类中的对象实例化

标签 unit-testing swift xctest objectinstantiation

我正在尝试测试我编写的类(class)。我添加了一个新的测试目标,并在其中导入了我要测试的类的目标。我的代码如下所示:

import XCTest
import TargetContainingClass

class Tests: XCTestCase
{
   var myClass = MyClass()

   // tests

}

但是,我得到了错误:

'MyClass' is not constructible with '()'

MyClass 不包含 init() 方法,因此不需要用任何东西构造。因此,我不明白我得到的错误。

如有任何帮助,我们将不胜感激。

干杯

最佳答案

您需要提供 init() 的实现:

class MyClass {
  init () {}
}

Swift 文档指出:

“Swift provides a default initializer for any structure or base class that provides 
 default values for all of its properties and does not provide at least one initializer
 itself. The default initializer simply creates a new instance with all of 
 its properties set to their default values.”  
    Apple Inc. “The Swift Programming Language.”

但以上显然不是真的;在行动中:

  1> class MyClass1 {}
  2> MyClass1()
/var/folders/.../expr.DO8uJ4.swift:2:1: error: 'MyClass1' is not constructible with '()'
MyClass1()
^
  2> class MyClass { 
  3.     init () {} 
  4. }    
  5> MyClass()
$R0: __lldb_expr_3.MyClass = {}

关于unit-testing - Swift - 测试类中的对象实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25096619/

相关文章:

node.js - 如何在 Node.js 中的 Sequelize Mock 中为 Sequelize.js 原始查询编写测试用例

ios - XCUITest - 如何检查 webview 是否已更新其内容?

xcode - Swift 泛型函数在测试中无法编译

Xcode6 beta 7 Swift 无法使用 UIPickerViewDataSource

ios - 查询 HealthKit 的相关性,但使用 anchor

xcode - 您如何通过电子邮件发送 Swift 自动化测试结果?

java - 处理私有(private)方法(白盒测试),具有许多条件的方法

java - 使用 PowerMock 模拟私有(private)方法

java - 在测试用例中覆盖 hibernate sessionfactory 的数据源

swift - 同时适用于 Android 和 IOS 应用程序的同一个 Parse 项目