首页 > 解决方案 > 如何在 XCode 中将字符串从一个单元测试传递到另一个单元测试?

问题描述

我有两个单元测试,testUserRegistration 和 testEmailConfirmation。注册测试首先运行,我创建一个唯一的电子邮件来注册一个随机的 int,例如 autoTest1234@test.com 或 autoTest4928@test.com。在下一个测试 testEmailConfirmation 中,我需要使用在上一个测试中创建的相同用户名。如何将它从一种测试方法发送到另一种测试方法?

标签: iosobjective-cxcodeunit-testing

解决方案


这不是您应该如何考虑单元测试的方式。

首先,您不应该对测试顺序进行评估:您的测试可能会以随机顺序运行,Xcode 决定,而不是您。您的测试应该彼此独立,并且您应该能够以任何顺序运行它们。在 Xcode 10 中,我们将进行测试并行化,您真的不希望它们相互依赖。最后,这种随机化可以很好地确保您的测试不会仅仅因为副作用而起作用。

基本上,您需要两个测试。

第一个看起来像这样:

func testUserRegistration() {
  // Given [an email address / username]
  // When [you run the registration flow]
  // Then [you assert that it worked]
}

现在该测试通过了,您可以认为您的用户注册有效,不应再次对其进行测试。没必要。这就是为什么它被称为“单元测试”,因为你测试“单元”。

现在在您的第二个测试中,您要测试的单元是“确认”部分:

func testEmailConfirmation() {
  // Given [new email/username, you can call the registration method with this new email here]
  // When [you apply your confirmation flow]
  // Then [you assert that the confirmation is working]
}

你可以调用另外一个随机邮件配置的用户注册功能(不是测试,真正的功能),并根据这封邮件做断言。

希望有帮助!


推荐阅读