提升代码可测试性与用户界面测试的实践指南
1. 优化代码以提高可测试性
在开发过程中,为了让代码更易于测试和维护,我们可以通过创建自定义数据模型来优化代码。以处理问题加载为例,让 QuestionsLoader
创建 Question
模型实例,而非返回 JSON 数据字典,这样不仅能让测试更有趣,还能使代码更加简洁。
以下是具体的操作步骤:
1. 定义 Question
模型 :创建一个名为 Question
的新 Swift 文件,并添加以下代码:
struct Question: Codable {
let title: String
let answerA: String
let answerB: String
let answerC: String
let correctAnswer: Int
}
- 定义响应容器 :由于模拟 JSON 数据包含问题列表,我们需要定义一个包含响应的
Codable
对象:
struct QuestionsFetchResponse: Codable {
let questions: [Question]
}
<