草庐IT

ios - 如何在 MVC 中测试 Controller 类?

coder 2023-09-08 原文

我正在根据 Model-View-Controller 在 Swift 中构建一个简单的 iOS 应用程序图案。我可以通过给它输入数据并根据我的预期断言输出结果来测试 Model 类。但我想知道如何测试 Controller 类?

看来如果真的要测试Controller类,测试逻辑会复杂很多。是否有测试 Controller 类的标准方法?

最佳答案

不要测试您的 UIViewController。他们身上发生了很多你看不到和/或无法控制的事情。相反,在其他对象(例如 View 模型)中保留尽可能多的逻辑,而不是在您的 UIViewController 中。然后,您可以测试 View 模型,就像测试模型一样。

编辑:

您可能希望如何构建您的 UIViewController 以及测试模型和 View 模型:

这段代码的主要收获是:

  1. 使用Dependency Injection
  2. 在 Release 中给类真正的依赖,在测试中给假的依赖

View Controller

// this class is super simple, so there's hardly any reason to test it now.
class SomeViewController: UIViewController {
    @IBOutlet weak var someLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        // we give the *real* user accessor in the view controller
        let viewModel = SomeViewModel(userAccessor: DBUserAccessor())
        someLabel.text = viewModel.welcomeMessage
    }
}

用户模型

struct User {
    var name: String
}

用户访问器

这是您的 View 模型需要的一些依赖项。在发布期间(在您的 View Controller 中)给出一个真实的。测试的时候给个假的,这样你就可以控制了。

protocol UserAccessor {
    var currentUser: User? { get }
}

// since we're using the fake version of this class to test the view model, you might want to test this class on its own
// you would do that using the same principles that I've shown (dependency injection).
class DBUserAccessor: UserAccessor {
    var currentUser: User? {
        // some real implementation that's used in your app
        // get the user from the DB
        return User(name: "Samantha") // so not really this line, but something from CoreData, Realm, etc.
    }
}

class FakeUserAccessor: UserAccessor {
    // some fake implementation that's used in your tests
    // set it to whatever you want your tests to "see" as the current User from the "DB"
    var currentUser: User?
}

查看模型

这是您要测试的实际逻辑所在的位置。

class SomeViewModel {
    let userAccessor: UserAccessor

    init(userAccessor: UserAccessor) {
        self.userAccessor = userAccessor
    }

    var welcomeMessage: String {
        if let username = self.username {
            return "Welcome back, \(username)"
        } else {
            return "Hello there!"
        }
    }

    var username: String? {
        return userAccessor.currentUser?.name
    }
}

测试

最后,您想如何测试它。

class SomeViewModelTest: XCTestCase {
    func testWelcomeMessageWhenNotLoggedIn() {
        let userAccessor = FakeUserAccessor()
        let viewModel = SomeViewModel(userAccessor: userAccessor) // we give the *fake* user accessor to the view model in tests
        userAccessor.currentUser = nil // set the fake UserAccessor to not have a user "logged in"

        // assert that the view model, which uses whatever you gave it, gives the correct message
        XCTAssertEqual(viewModel.welcomeMessage, "Hello there!")
    }

    func testWelcomeMessageWhenLoggedIn() {
        let userAccessor = FakeUserAccessor()
        let viewModel = SomeViewModel(userAccessor: userAccessor)
        userAccessor.currentUser = User(name: "Joe") // this time, the use is "logged in"

        XCTAssertEqual(viewModel.welcomeMessage, "Welcome back, Joe") // and we get the correct message
    }
}

关于ios - 如何在 MVC 中测试 Controller 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38548258/

有关ios - 如何在 MVC 中测试 Controller 类?的更多相关文章

  1. ruby-on-rails - 使用 Ruby on Rails 进行自动化测试 - 最佳实践 - 2

    很好奇,就使用ruby​​onrails自动化单元测试而言,你们正在做什么?您是否创建了一个脚本来在cron中运行rake作业并将结果邮寄给您?git中的预提交Hook?只是手动调用?我完全理解测试,但想知道在错误发生之前捕获错误的最佳实践是什么。让我们理所当然地认为测试本身是完美无缺的,并且可以正常工作。下一步是什么以确保他们在正确的时间将可能有害的结果传达给您? 最佳答案 不确定您到底想听什么,但是有几个级别的自动代码库控制:在处理某项功能时,您可以使用类似autotest的内容获得关于哪些有效,哪些无效的即时反馈。要确保您的提

  2. ruby - 如何在 Ruby 中顺序创建 PI - 2

    出于纯粹的兴趣,我很好奇如何按顺序创建PI,而不是在过程结果之后生成数字,而是让数字在过程本身生成时显示。如果是这种情况,那么数字可以自行产生,我可以对以前看到的数字实现垃圾收集,从而创建一个无限系列。结果只是在Pi系列之后每秒生成一个数字。这是我通过互联网筛选的结果:这是流行的计算机友好算法,类机器算法:defarccot(x,unity)xpow=unity/xn=1sign=1sum=0loopdoterm=xpow/nbreakifterm==0sum+=sign*(xpow/n)xpow/=x*xn+=2sign=-signendsumenddefcalc_pi(digits

  3. ruby - 如何在 buildr 项目中使用 Ruby 代码? - 2

    如何在buildr项目中使用Ruby?我在很多不同的项目中使用过Ruby、JRuby、Java和Clojure。我目前正在使用我的标准Ruby开发一个模拟应用程序,我想尝试使用Clojure后端(我确实喜欢功能代码)以及JRubygui和测试套件。我还可以看到在未来的不同项目中使用Scala作为后端。我想我要为我的项目尝试一下buildr(http://buildr.apache.org/),但我注意到buildr似乎没有设置为在项目中使用JRuby代码本身!这看起来有点傻,因为该工具旨在统一通用的JVM语言并且是在ruby中构建的。除了将输出的jar包含在一个独特的、仅限ruby​​

  4. ruby - 什么是填充的 Base64 编码字符串以及如何在 ruby​​ 中生成它们? - 2

    我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%

  5. ruby-on-rails - 渲染另一个 Controller 的 View - 2

    我想要做的是有2个不同的Controller,client和test_client。客户端Controller已经构建,我想创建一个test_clientController,我可以使用它来玩弄客户端的UI并根据需要进行调整。我主要是想绕过我在客户端中内置的验证及其对加载数据的管理Controller的依赖。所以我希望test_clientController加载示例数据集,然后呈现客户端Controller的索引View,以便我可以调整客户端UI。就是这样。我在test_clients索引方法中试过这个:classTestClientdefindexrender:template=>

  6. ruby - 使用 C 扩展开发 ruby​​gem 时,如何使用 Rspec 在本地进行测试? - 2

    我正在编写一个包含C扩展的gem。通常当我写一个gem时,我会遵循TDD的过程,我会写一个失败的规范,然后处理代码直到它通过,等等......在“ext/mygem/mygem.c”中我的C扩展和在gemspec的“扩展”中配置的有效extconf.rb,如何运行我的规范并仍然加载我的C扩展?当我更改C代码时,我需要采取哪些步骤来重新编译代码?这可能是个愚蠢的问题,但是从我的gem的开发源代码树中输入“bundleinstall”不会构建任何native扩展。当我手动运行rubyext/mygem/extconf.rb时,我确实得到了一个Makefile(在整个项目的根目录中),然后当

  7. ruby-on-rails - 如何在 ruby​​ 中使用两个参数异步运行 exe? - 2

    exe应该在我打开页面时运行。异步进程需要运行。有什么方法可以在ruby​​中使用两个参数异步运行exe吗?我已经尝试过ruby​​命令-system()、exec()但它正在等待过程完成。我需要用参数启动exe,无需等待进程完成是否有任何ruby​​gems会支持我的问题? 最佳答案 您可以使用Process.spawn和Process.wait2:pid=Process.spawn'your.exe','--option'#Later...pid,status=Process.wait2pid您的程序将作为解释器的子进程执行。除

  8. ruby - Ruby 的 Hash 在比较键时使用哪种相等性测试? - 2

    我有一个围绕一些对象的包装类,我想将这些对象用作散列中的键。包装对象和解包装对象应映射到相同的键。一个简单的例子是这样的:classAattr_reader:xdefinitialize(inner)@inner=innerenddefx;@inner.x;enddef==(other)@inner.x==other.xendenda=A.new(o)#oisjustanyobjectthatallowso.xb=A.new(o)h={a=>5}ph[a]#5ph[b]#nil,shouldbe5ph[o]#nil,shouldbe5我试过==、===、eq?并散列所有无济于事。

  9. ruby - 如何在续集中重新加载表模式? - 2

    鉴于我有以下迁移:Sequel.migrationdoupdoalter_table:usersdoadd_column:is_admin,:default=>falseend#SequelrunsaDESCRIBEtablestatement,whenthemodelisloaded.#Atthispoint,itdoesnotknowthatusershaveais_adminflag.#Soitfails.@user=User.find(:email=>"admin@fancy-startup.example")@user.is_admin=true@user.save!ende

  10. ruby - RSpec - 使用测试替身作为 block 参数 - 2

    我有一些Ruby代码,如下所示:Something.createdo|x|x.foo=barend我想编写一个测试,它使用double代替block参数x,这样我就可以调用:x_double.should_receive(:foo).with("whatever").这可能吗? 最佳答案 specify'something'dox=doublex.should_receive(:foo=).with("whatever")Something.should_receive(:create).and_yield(x)#callthere

随机推荐