【问题标题】:Preconditions in Swift and Testing ThemSwift 中的先决条件和测试
【发布时间】:2015-02-22 12:43:03
【问题描述】:

在 Java 中,我可以使用 Guava 之类的框架来检查方法的前置条件,例如:

public void doSomething(int index) {
  Preconditions.checkArgument(index >= 3);
  // do something
}

然后我可以像这样测试它们:

@Test(expected = IllegalArgumentException.class)
public void testDoSomething() {
  sut.doSomething(2);
}

如何在 Swift 中做同样的事情?

我知道 Swift 的断言,但我不知道你会如何测试它们。

【问题讨论】:

    标签: swift testing assertions


    【解决方案1】:

    您还可以通过precondition 在 Swift 中使用前置条件。像这样:

    func test(hello:String){
        precondition(hello == "Hello", "String is Hello")
    
    }
    

    例如,在 Swift REPL 中:

    > test("Hello")
    > test("Hellox")
    precondition failed: String is Hello: file /var/folders/z3/kd0nj4ln1rgcpm8bdz7067wh0000gs/T/./lldb/566/repl1.swift, line 2
    Execution interrupted. Enter Swift code to recover and continue.
    

    【讨论】:

    • @GoZoner 感谢您的编辑。还不知道 Swift REPL。
    • 还有……怎么写对应的测试呢?
    猜你喜欢
    • 2018-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多