我正在尝试测试我编写的类(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/