我正在尝试测试这个类(Swiftris/Swifteris/Array2D.swift
):
class Array2D<T> {
let rows: Int
let columns: Int
var array: Array<T?>
init(rows: Int, columns: Int) {
self.rows = rows
self.columns = columns
array = Array<T?>(count:rows * columns, repeatedValue: nil)
}
subscript(column: Int, row: Int) -> T? {
get {
return array[(row * columns) + column]
}
set {
array[(row * columns) + column] = newValue
}
}
}
通过这个简单的测试(Swiftris/SwiftrisTests/Array2DTest.swift
):
import UIKit
import XCTest
class Array2DTest: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
func testHasRows() {
var array: Array2D = Array2D(rows: 10, columns: 15)
XCTAssertEqual(array.rows, 20, "an Array2D instance should have the correct number of rows")
}
}
无法解释无法解析Array2D:
Swifteris/SwifterisTests/Array2DTest.swift:12:20: Use of undeclared type 'Array2D'
我是否需要将自己的模块导入我的测试?这非常令人费解,因为我在另一个项目中做了完全相同的瘦,并且没有解决被测试类的问题。
答案 0 :(得分:3)
您有2个选项。
Array2D.swift
添加到SwifterisTests
目标会员这很简单
Swifteris
导入Array2DTest.swift
基本上推荐这种方法,但它相对比较烦人。
首先,您必须将所有可测试类/方法/属性声明为public
:
Array2D.swift:
public class Array2D<T> {
public let rows: Int
public let columns: Int
private var array: Array<T?>
public init(rows: Int, columns: Int) {
self.rows = rows
self.columns = columns
array = Array<T?>(count:rows * columns, repeatedValue: nil)
}
public subscript(column: Int, row: Int) -> T? {
get {
return array[(row * columns) + column]
}
set {
array[(row * columns) + column] = newValue
}
}
}
然后,将主模块Swifteris
导入测试模块SwifterisTests
import XCTest
import Swifteris
// Here Array2D is avaiable.
有关此问答的更多讨论:Swift, access modifiers and unit testing