在 Swift 测试驱动开发中对 @ObservableObject 进行单元测试 [英] Unit testing an @ObservableObject in Swift Test Driven Development

查看:40
本文介绍了在 Swift 测试驱动开发中对 @ObservableObject 进行单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习如何将 MVVM 架构与 TDD 结合使用,以解决无法在 SwiftUI 中对视图进行单元测试的一些问题.

I'm trying to learn how to use MVVM architecture with TDD to solve some of the problems with not being able to unit test Views in SwiftUI.

我有一个带日期的警报结构:

I have an Alarm struct which takes a date:

import Foundation

struct Alarm {
    var time: Date
}

我有一个基本的

class AlarmPickerViewModel: ObservableObject {
    @Published var alarm: Alarm

    init(alarm: Alarm) {
        self.alarm = alarm
    }

}

如果 AlarmPickerViewModel 不是 ObservableObject 的子类并且警报属性不是 <代码>@Published.

I'm struggling to work out how to write a unit test that fails if the AlarmPickerViewModel isn't a subclass of ObservableObject and the alarm property isn't @Published.

我在网站上查看了这个问题 但它似乎对我没有帮助.

I've looked at this question on the site but it doesn't seem to help me.

请指出我哪里出错了?

推荐答案

如果alarm 不是@Published,您可以创建一个甚至无法编译的测试创建对该属性的订阅,因为您只有在 @Published 时才能订阅它.

You can create a test that won't even compile if alarm is not @Published by simply creating a subscription to that property, since you will only be able to subscribe to it if it is @Published.

ObservableObject 一致性为您的对象添加了一个 objectWillChange Publisher,因此要测试它,您只需订阅该 发布者.如果 AlarmPickerViewModel 不是 ObservableObject,测试甚至不会编译.

The ObservableObject conformance adds an objectWillChange Publisher to your object, so to test that, you simply need to subscribe to that Publisher. If AlarmPickerViewModel wasn't ObservableObject, the test won't even compile.

func testAlarmPickerViewModel() {
    let alarmPickerViewModel = AlarmPickerViewModel(alarm: Alarm(time: .distantFuture))

    alarmPickerViewModel.$alarm.sink(receiveValue: { print("ViewModel.alarm updated, new value: \($0)") })

    alarmPickerViewModel.objectWillChange.sink(receiveValue: { print("ViewModel updated: \($0)")})
}

这篇关于在 Swift 测试驱动开发中对 @ObservableObject 进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆