2. Unity3D 结合实际项目实现单元测试

被测项目背景介绍

这里只介绍项目中的一个 UI 模块。如下图所示,在整个 UI 模块中有很多子模块,在业务上各个子 UI 模块之间会经常需要来回切换。那么如何去实现该功能呢?在频繁的 UI 状态切换中又如何保证其正确性呢?

状态机的概念

答案就是:状态机。举个例子来帮助大家了解状态机的含义。每个上班族大概每天要干的事就是:早上起来去上班、到下班时间下班回家、困了累了上床睡觉。那么上班族一天的状态就有:上班、下班、睡觉;状态的转换条件有:早上会去上班、晚上下班、12点后睡觉;触发状态的转换条件有:到早上了就起床去上班、到晚上了就下班、12点了就睡觉。

项目中的状态机

根据我们对状态机的理解,假设在项目中 UI 子模块有三个:老弱帮扶专题、智慧人房专题和视频监控专题,那么它的状态机(包括各个状态及其转换条件)可以用下图表示:

EditMode 模式下的测试

被测函数说明

其实上面 UI 各个专题状态的转换,有个核心函数,它的流程图大致如下:

对应的实际代码如下所示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public void ChangeTo(string type)
{
string lastID = string.Empty;
this.GetLastID(ref lastID);
if(type == lastID)
{
this.EndAllStates();
}
else
{
var entry = m_entries.TryGetNullableValue(type);
if(entry != null)
{
this.EndAllStates();
this.AddState(entry);
}
}
}

测试用例设计

针对这个核心函数,对其进行测试用例设计:

  1. 点击某个状态,且上一状态为空;
  2. 点击某个状态,且与上一状态相同;
  3. 点击某个状态,且与上一状态不相同;
  4. 点击某个状态,但状态为Null;
  5. 点击某个状态,但状态未注册。

然后编写测试代码:

1~3 条测试用例代码
  1. 1~3 测试用例代码如下所示:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
using System.Collections.Generic;
using UnityEngine;
using Module.FSM;
using InternalModule.FSM;

using NUnit.Framework;
using Assets.UnitTest.Utils;
//using NSubstitute;

namespace Assets.UnitTest.Editor.EditeModeTestDemo
{
[TestFixture]
class ThemeEntryManagerNormalTest
{
ThemeEntryManager entryManager;
List<FSMState<string>> themeStates;
Dictionary<string, ThemeEntry> themeEntries;
ThemeEntry themeEntryTest1Instance;
ThemeEntry themeEntryTest1;
string type1;
string lastID;

[SetUp]
public void SetUp()
{
type1 = "ThemeEntry1";
themeEntryTest1 = ThemeEntry.Create(type1, "test1", new GameObject("test1"));
entryManager = ThemeEntryManager.Instance;
//注册ThemeEntry
entryManager.SetEntry(type1, themeEntryTest1);

themeStates = ReflectionUtils
.CallPrivateField<List<FSMState<string>>>(ThemeEntryManager.Instance, "m_subStates", null);
themeEntries = ReflectionUtils
.CallPrivateField<Dictionary<string, ThemeEntry>>(ThemeEntryManager.Instance, "m_entries", null);
themeEntryTest1Instance = themeEntries.TryGetNullableValue(type1);
lastID = null;
entryManager.GetLastID(ref lastID);

//校验是否注册成功,上一状态是否为空
Assert.IsFalse(themeStates.Contains(themeEntryTest1));
Assert.IsTrue(themeEntryTest1 == themeEntryTest1Instance);
Assert.IsNull(lastID);

//模拟点击,初始化数据
entryManager.ChangeTo(type1);
entryManager.GetLastID(ref lastID);
themeStates = ReflectionUtils
.CallPrivateField<List<FSMState<string>>>(ThemeEntryManager.Instance, "m_subStates", null);
themeEntries = ReflectionUtils
.CallPrivateField<Dictionary<string, ThemeEntry>>(ThemeEntryManager.Instance, "m_entries", null);
themeEntryTest1Instance = themeEntries.TryGetNullableValue(type1);

//校验当前状态是否切换成功,是否成功转为上一状态
Assert.IsTrue(string.Equals(type1, lastID));
Assert.AreEqual(1, themeStates.Count);
Assert.IsTrue(themeStates.Contains(themeEntryTest1));
Assert.IsTrue(themeEntryTest1 == themeEntryTest1Instance);
}
[TearDown]
public void TearDown()
{
Object.DestroyImmediate(ThemeEntryManager.Instance);
}

[TestCase]
[Description("点击某个状态,且上一状态为空")]
public void ChangeThemeEntryStatusButLastThemeEntryStatusIsNullTest()
{
//set SetUp();
}
[TestCase]
[Description("点击某个状态,且与上一状态相同")]
public void ChangeThemeEntryStatusCurrentThemeEntryStatusIsSameAsTheLastStatusTest()
{
//模拟与上一状态一样时的点击
entryManager.ChangeTo(type1);
entryManager.GetLastID(ref lastID);
themeStates = ReflectionUtils
.CallPrivateField<List<FSMState<string>>>(ThemeEntryManager.Instance, "m_subStates", null);
themeEntries = ReflectionUtils
.CallPrivateField<Dictionary<string, ThemeEntry>>(ThemeEntryManager.Instance, "m_entries", null);
themeEntryTest1Instance = themeEntries.TryGetNullableValue(type1);

//校验状态是否回到初始状态
Assert.IsTrue(string.Equals(type1, lastID));
Assert.AreEqual(0, themeStates.Count);
Assert.IsTrue(themeEntryTest1 == themeEntryTest1Instance);
}

[TestCase]
[Description("点击某个状态,且与上一状态不相同")]
public void ChangeThemeEntryStatusCurrentThemeEntryStatusIsDifferentTheLastStatusTest()
{
string type2 = "ThemeEntryTwo";
ThemeEntry themeEntryTest2 = ThemeEntry.Create(type2, "test2", new GameObject("test2"));
//注册ThemeEntry
entryManager.SetEntry(type2, themeEntryTest2);

//模拟与上一状态不一样时的点击
entryManager.ChangeTo(type2);
entryManager.GetLastID(ref lastID);
themeStates = ReflectionUtils
.CallPrivateField<List<FSMState<string>>>(ThemeEntryManager.Instance, "m_subStates", null);
themeEntries = ReflectionUtils
.CallPrivateField<Dictionary<string, ThemeEntry>>(ThemeEntryManager.Instance, "m_entries", null);
ThemeEntry themeEntryTest2Instance = themeEntries.TryGetNullableValue(type2);

//校验状态是否回到初始状态
Assert.IsTrue(string.Equals(type2, lastID));
Assert.AreEqual(1, themeStates.Count);
Assert.IsTrue(themeStates.Contains(themeEntryTest2));
Assert.IsTrue(themeEntryTest2 == themeEntryTest2Instance);
}
}
}
4~5 条测试用例代码
  1. 4~5 测试用例代码如下所示:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
using System.Collections.Generic;
using UnityEngine;
using Module.FSM;
using InternalModule.FSM;

using NUnit.Framework;
using Assets.UnitTest.Utils;
//using NSubstitute;

namespace Assets.UnitTest.Editor.EditeModeTestDemo
{
[TestFixture]
class ThemeEntryManagerAbnormalTest
{
[TearDown]
public void TearDown()
{
Object.DestroyImmediate(ThemeEntryManager.Instance);
}

[TestCase]
[Description("点击某个状态,但状态为Null")]
public void ChangeThemeEntryStatusButTheThemeEntryStatusIsNullTest()
{
string type1 = null ;
//string type1 = string.Empty ;
ThemeEntryManager.Instance.ChangeTo(type1);

ThemeEntryManager entryManager = ThemeEntryManager.Instance;
string lastID = null;
entryManager.GetLastID(ref lastID);
List<FSMState<string>> themeStates = ReflectionUtils
.CallPrivateField<List<FSMState<string>>>(ThemeEntryManager.Instance, "m_subStates", null);
Dictionary<string, ThemeEntry> themeEntries = ReflectionUtils
.CallPrivateField<Dictionary<string, ThemeEntry>>(ThemeEntryManager.Instance, "m_entries", null);
ThemeEntry themeEntryTest1Instance = themeEntries.TryGetNullableValue(type1);

Assert.AreEqual(0, themeStates.Count);
Assert.IsNull(lastID);
Assert.IsNull(themeEntryTest1Instance);
}

[TestCase]
[Description("点击某个状态,但状态未注册")]
public void ChangeThemeEntryStatusButTheThemeEntryStatusNoRegisteredTest()
{
string type1 = "ThemeEntry1";
ThemeEntryManager.Instance.ChangeTo(type1);

ThemeEntryManager entryManager = ThemeEntryManager.Instance;
string lastID = null;
entryManager.GetLastID(ref lastID);
List<FSMState<string>> themeStates = ReflectionUtils
.CallPrivateField<List<FSMState<string>>>(ThemeEntryManager.Instance, "m_subStates", null);
Dictionary<string, ThemeEntry> themeEntries = ReflectionUtils
.CallPrivateField<Dictionary<string, ThemeEntry>>(ThemeEntryManager.Instance, "m_entries", null);
ThemeEntry themeEntryTest1Instance = themeEntries.TryGetNullableValue(type1);

Assert.AreEqual(0, themeStates.Count);
Assert.IsNull(lastID);
Assert.IsNull(themeEntryTest1Instance);
}
}
}

执行测试

测试结果

测试结果分析

从测试结果可以看出,5 条测试用例都成功了 4 条,失败了 1 条。失败的原因是因为 ChangeTo() 函数对传入的参数没有校验是否为 null 的原因。

PlayMode 模式的测试

测试用例设计

这里我们以”老弱帮扶”专题为被测试对象,并对其设计测试用例:

  1. 老弱帮扶信息概览;
  2. 统计栏下点击老弱分布开关;
  3. 服务栏下点击数字设备开关;
  4. 分别在统计栏和服务拦下按右上角关闭按钮;
  5. 在老弱帮扶专题状态下点击其他专题按钮;
  6. 多次重复点击老弱帮扶专题;
  7. 从其他专题状态下点击老弱帮扶专题。

对应的测试代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
using Module.UI;
using Module.FSM;
using Core;

using NUnit.Framework;
using UnityEngine.TestTools;
using Assets.UnitTest.Utils;
using Assets.UnitTest.PageObject;
//using NSubstitute;

namespace Assets.UnitTest.Player
{
class OldWeakThemeTest
{
public GameObject OldWeakBtn;
public GameObject Service;
public OldWeakServiceProCtr oldWeakServiceProCtr;
bool hasLoaded = false;

[OneTimeSetUp]
public void OnTimeSetUp()
{
//加载基础场景
Module.Controller.SceneResourcesLoad.Instance.LoadScenes();

UnityEngine.SceneManagement.SceneManager.sceneLoaded += (_scene, _mode) =>
{
Common.CommonDebug.Log(_scene.name, Color.green);
//BasicesScene为最后一个加载的场景
if (_scene.name == "BasicsScene")
{
hasLoaded = true;
Debug.Log("场景加载完成.");
}
};
}

[TearDown]
public void TearDown()
{
GameObject oldWeakMenu = GameObject.Find(OldWeakPage.OldWeakMenuPath);
if (oldWeakMenu.activeSelf)
{
GameObject oldWeakMenuCloseBtn = GameObject.Find(OldWeakPage.OldWeakMenuCloseBtn);
UserSimulateUtils.Click(oldWeakMenuCloseBtn);
}
}

[UnityTest]
//[Timeout(1000000)]
[Description("老弱帮扶信息概览")]
public IEnumerator OldWeakInfoOverviewTest()
{
//等待场景加载完成
while (hasLoaded == false)
{
Debug.Log("场景还没加载完成.");
yield return null;
}

//点击老弱帮扶专题按钮
clickOldWeakThemeBtn();

bool isTrue = checkStatisticsState();
bool isFalse = checkServiceState();
Assert.IsTrue(isTrue);
Assert.IsFalse(isFalse);

//统计栏和服务栏重复点击
for (int i = 0; i < 2; i++)
{
//点击OldWeakBtn后,默认切换到统计栏
clickServiceBtn();
isTrue = checkServiceState();
isFalse = checkStatisticsState();
Assert.IsTrue(isTrue);
Assert.IsFalse(isFalse);

clickStatisticsBtn();
isTrue = checkStatisticsState();
isFalse = checkServiceState();
Assert.IsTrue(isTrue);
Assert.IsFalse(isFalse);
}
}

[UnityTest]
[Description("统计栏下点击老弱分布开关")]
public IEnumerator ClickOldWeakDistributionSwitchTest()
{
//等待场景加载完成
while (hasLoaded == false)
{
Debug.Log("场景还没加载完成.");
yield return null;
}

//点击老弱帮扶专题按钮,默认老弱分布开关打开
clickOldWeakThemeBtn();
yield return null;
bool isTrue = checkOldWeakDistributionState();
Assert.IsTrue(isTrue);

for (int i = 1; i <= 4; i++)
{
if (i % 2 == 0)
{
//点偶数次,老弱分布开关打开
clickOldWeakDistributionBtn();
yield return null;
isTrue = checkOldWeakDistributionState();
Assert.IsTrue(isTrue);
}
else
{
//点奇数次,老弱分布开关关闭
clickOldWeakDistributionBtn();
yield return null;
bool isFalse = checkOldWeakDistributionState();
Assert.IsFalse(isFalse);
}
}
}

[UnityTest]
[Description("服务栏下点击数字设备开关")]
public IEnumerator ClickDigitalDeviceSwitchTest()
{
//等待场景加载完成
while (hasLoaded == false)
{
Debug.Log("场景还没加载完成.");
yield return null;
}

//点击老弱帮扶专题按钮,然后再点击服务按钮,切换到服务栏下
clickOldWeakThemeBtn();
yield return null;
clickServiceBtn();
yield return null;
bool isTrue = checkDigitalDeviceState();
Assert.IsTrue(isTrue);

for (int i = 1; i <= 4; i++)
{
if (i % 2 == 0)
{
//点偶数次,数字设备开关打开
clickDigitalDeviceBtn();
yield return null;
isTrue = checkDigitalDeviceState();
Assert.IsTrue(isTrue);
}
else
{
//点奇数次,数字设备开关关闭
clickDigitalDeviceBtn();
yield return null;
bool isFalse = checkDigitalDeviceState();
Assert.IsFalse(isFalse);
}
}
}

[UnityTest]
[Description("分别在统计栏和服务拦下按右上角关闭按钮")]
public IEnumerator ClickCloseBtnInStatisticsAndServiceTest()
{
//等待场景加载完成
while (hasLoaded == false)
{
Debug.Log("场景还没加载完成.");
yield return null;
}

//统计栏下按右上角关闭按钮
clickOldWeakThemeBtn();
yield return null;
clickCloseBtn();
yield return null;
bool isfalse = checkOldWeakMenuState();
Assert.IsFalse(isfalse);

//在服务拦下按右上角关闭按钮
clickOldWeakThemeBtn();
yield return null;
clickServiceBtn();
yield return null;
clickCloseBtn();
yield return null;
isfalse = checkOldWeakMenuState();
Assert.IsFalse(isfalse);
}

[UnityTest]
[Description("在老弱帮扶专题状态下点击其他专题按钮")]
public IEnumerator ClickOtherThemeInOldWeakStateTest()
{
//等待场景加载完成
while (hasLoaded == false)
{
Debug.Log("场景还没加载完成.");
yield return null;
}

//在老弱帮扶的统计栏下点击其他专题
clickOldWeakThemeBtn();
yield return null;
clickOtherThemeBtn();
yield return null;
bool isfalse = checkOldWeakMenuState();
Assert.IsFalse(isfalse);
bool isTrue = checkOtherThemeMenuState();
Assert.IsTrue(isTrue);

//在老弱帮扶的服务栏下点击其他专题
clickOldWeakThemeBtn();
yield return null;
clickServiceBtn();
yield return null;
isTrue = checkServiceState();
Assert.IsTrue(isTrue);
clickOtherThemeBtn();
yield return null;
isfalse = checkOldWeakMenuState();
Assert.IsFalse(isfalse);
isTrue = checkOtherThemeMenuState();
Assert.IsTrue(isTrue);
}

[UnityTest]
[Description("多次重复点击老弱帮扶专题")]
public IEnumerator RepeatedlyClickOldWeakThemeTest()
{
//等待场景加载完成
while (hasLoaded == false)
{
Debug.Log("场景还没加载完成.");
yield return null;
}

//多次重复点击老弱帮扶专题
for (int i = 1; i <= 10; i++)
{
clickOldWeakThemeBtn();
yield return null;
bool isOn = checkOldWeakMenuState();
if (i % 2 == 0)
Assert.IsFalse(isOn);
else
Assert.IsTrue(isOn);
}
}

[UnityTest]
[Description("从其他专题状态下点击老弱帮扶专题")]
public IEnumerator ClickOldWeakThemeInOtherThemeTest()
{
//等待场景加载完成
while (hasLoaded == false)
{
Debug.Log("场景还没加载完成.");
yield return null;
}

//从其他专题状态下点击老弱帮扶专题
clickOtherThemeBtn();
yield return null;
bool isTrue = checkOtherThemeMenuState();
bool isFalse = checkOldWeakMenuState();
Assert.IsTrue(isTrue);
Assert.IsFalse(isFalse);
clickOldWeakThemeBtn();
yield return null;
isTrue = checkOldWeakMenuState();
isFalse = checkOtherThemeMenuState();
Assert.IsTrue(isTrue);
Assert.IsFalse(isFalse);
}

//点击老弱帮扶专题按钮
private bool clickOldWeakThemeBtn()
{
OldWeakBtn = GameObject.Find(OldWeakPage.OldWeakBtnPath);
if (OldWeakBtn)
{
UserSimulateUtils.Click(OldWeakBtn);
return true;
}
return false;
}

//点击老弱帮扶菜单的统计按钮
private void clickStatisticsBtn()
{
GameObject statistics = GameObject.Find(OldWeakPage.StatisticsPath);
if (statistics)
{
UserSimulateUtils.Click(statistics);
}
}

//点击老弱帮扶菜单的服务按钮
private void clickServiceBtn()
{
GameObject service = GameObject.Find(OldWeakPage.ServicePath);
if (service)
{
UserSimulateUtils.Click(service);
}
}

//点击老弱帮扶菜单的关闭按钮
private void clickCloseBtn()
{
GameObject closeBtn = GameObject.Find(OldWeakPage.OldWeakMenuCloseBtn);
if (closeBtn)
{
UserSimulateUtils.Click(closeBtn);
}
}

//点击老弱帮扶专题统计栏下的老弱分布按钮
private void clickOldWeakDistributionBtn()
{
GameObject closeBtn = GameObject.Find(OldWeakPage.OldWeakDistributionPath);
if (closeBtn)
{
bool b = UserSimulateUtils.Click(closeBtn);
}
}

//点击老弱帮扶专题服务栏下的数字设备按钮
private void clickDigitalDeviceBtn()
{
GameObject closeBtn = GameObject.Find(OldWeakPage.DigitalDevicePath);
if (closeBtn)
{
UserSimulateUtils.Click(closeBtn);
}
}

//点击其他主题按钮
private void clickOtherThemeBtn()
{
GameObject otherThemeBtn = GameObject.Find(OldWeakPage.OtherThemeBtnPath);
if (otherThemeBtn)
{
UserSimulateUtils.Click(otherThemeBtn);
}
}

//检查当前是否在统计状态
private bool checkStatisticsState()
{
GameObject statistics = GameObject.Find(OldWeakPage.StatisticsPath);
Toggle statisticsToggle = statistics.GetComponent<Toggle>();
return statisticsToggle.isOn;
}

//检查当前是否在服务状态
private bool checkServiceState()
{
GameObject service = GameObject.Find(OldWeakPage.ServicePath);
Toggle serviceToggle = service.GetComponent<Toggle>();
return serviceToggle.isOn;
}

//检查老弱分布的状态
private bool checkOldWeakDistributionState()
{
GameObject building = GameObject.Find(OldWeakPage.BuildingPath);
return building.activeSelf;
}

//检查数字设备的状态
private bool checkDigitalDeviceState()
{
GameObject projection = GameObject.Find(OldWeakPage.OldWeakServiceProjectionPath);
return projection.activeSelf;
}

//检查老弱帮扶菜单的状态
private bool checkOldWeakMenuState()
{
GameObject oldWeakMenu = GameObject.Find(OldWeakPage.OldWeakMenuPath);
return oldWeakMenu.activeSelf;
}

//检查其他主题的状态
private bool checkOtherThemeMenuState()
{
GameObject otherThemeMenu = GameObject.Find(OldWeakPage.OtherThemeMenuPath);
return otherThemeMenu.activeSelf;
}
}
}

执行测试

总结

在 U3D 中进行单元测试,我们是这么定位 Editmode 和 PlayMode 的:EditMode用于模块内的单元测试(与业务无关);PlayMode用于模拟用户的UI测试(结合业务)。另外关于如何设计测试框架,如何编写测试用例,如何才能方便后续代码的维护等等问题就是以后要考虑的问题了。