|
@@ -0,0 +1,502 @@
|
|
1
|
+# 用到的组件
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+本篇涉及的测试形式:
|
|
6
|
+
|
|
7
|
+- `Subcutaneous`测试:最接近`UI`层的测试,聚焦在输入和输出,非常适合逻辑和UI分离的场景,这样就避免进行UI测试,容易写也容易维护
|
|
8
|
+- `Integration`集成测试:
|
|
9
|
+- `Unit`单元测试:
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+## `FluentAssertions`组件
|
|
14
|
+
|
|
15
|
+- 支持非常自然地规定自动测试的结果
|
|
16
|
+- 更好的可读性
|
|
17
|
+- 更好的测试失败说明
|
|
18
|
+- 避免调试
|
|
19
|
+- 更有生产力,更简单
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+## `Moq`组件
|
|
24
|
+
|
|
25
|
+- 为`.NET`而来
|
|
26
|
+- 流行并且友好
|
|
27
|
+- 支持`Mock`类和接口
|
|
28
|
+- 强类型,这样可以避免和系统关键字冲突
|
|
29
|
+- 简单易用
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+## `EF Core InMemory`组件
|
|
34
|
+
|
|
35
|
+- 内置数据库引擎
|
|
36
|
+- 内存数据库
|
|
37
|
+- 适用于测试场景
|
|
38
|
+- 轻量级无依赖
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+## `Respawn`组件
|
|
43
|
+
|
|
44
|
+- 为集成测试准备的数据库智能清洗
|
|
45
|
+- 避免删除数据或回滚事务
|
|
46
|
+- 把数据库恢复到一个干净的某个节点
|
|
47
|
+- 忽略表和`Schema`,比如忽略`_EFMigrationsHistory`
|
|
48
|
+- 支持`SQL Server`, `Postgres`,`MySQL`
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+# 界面
|
|
53
|
+
|
|
54
|
+## 列表
|
|
55
|
+
|
|
56
|
+![t1](F:\SourceCodes\DDWiki\专题\后端\测试\t1.png)
|
|
57
|
+
|
|
58
|
+## 删除和更新
|
|
59
|
+
|
|
60
|
+![t2](F:\SourceCodes\DDWiki\专题\后端\测试\t2.png)
|
|
61
|
+
|
|
62
|
+# 解决方案组件依赖
|
|
63
|
+
|
|
64
|
+- `.NET Core Template Package`
|
|
65
|
+- `ASP.NET Core 3.1`
|
|
66
|
+- `Entity Framework Core 3.1`
|
|
67
|
+- `ASP.NET Core Identity 3.1`
|
|
68
|
+- `Angular 9`
|
|
69
|
+
|
|
70
|
+# 文件结构
|
|
71
|
+
|
|
72
|
+- `Application`层
|
|
73
|
+- `Domain`层
|
|
74
|
+- `Infrastructure`层
|
|
75
|
+- `WebUI`层
|
|
76
|
+- 集成测试层
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+# `WebUI`层
|
|
81
|
+
|
|
82
|
+`TodoListsController`
|
|
83
|
+
|
|
84
|
+```
|
|
85
|
+[Authorize]
|
|
86
|
+public class TodoListsController : ApiController
|
|
87
|
+{
|
|
88
|
+ [HttpGet]
|
|
89
|
+ public async Task<IActionResult<TodoVm>> Get()
|
|
90
|
+ {
|
|
91
|
+ return await Mediator.Send(new GetTodosQuery());
|
|
92
|
+ }
|
|
93
|
+
|
|
94
|
+ [HttpGet("{id}")]
|
|
95
|
+ public async Task<FileResult> Get(int id)
|
|
96
|
+ {
|
|
97
|
+ var vm = await Mediator.Send(new ExportTodosQuery {ListId=id});
|
|
98
|
+ return File(vm.Content, vm.ContentType, vm.FileName);
|
|
99
|
+ }
|
|
100
|
+
|
|
101
|
+ [HttpPost]
|
|
102
|
+ public async Task<IActionResult<int>> Create(CreateTodoListCommand command)
|
|
103
|
+ {
|
|
104
|
+ return await Mediator.Send(command);
|
|
105
|
+ }
|
|
106
|
+}
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+```
|
|
110
|
+
|
|
111
|
+# `Application`层
|
|
112
|
+
|
|
113
|
+`GetTodosQuery.cs`
|
|
114
|
+
|
|
115
|
+```
|
|
116
|
+public class GetTodosQuery : IRequest<TodosVm>
|
|
117
|
+{
|
|
118
|
+
|
|
119
|
+}
|
|
120
|
+
|
|
121
|
+public class GetTodosQueryHandler : IRequestHandler<GetTodosQuery, TodosVm>
|
|
122
|
+{
|
|
123
|
+ private readonly IApplicationDbContext _context;
|
|
124
|
+ private readonly IMapper _mapper;
|
|
125
|
+
|
|
126
|
+ public GetTodosQueryHandler(IApplicationDbContext context, IMapper mapper)
|
|
127
|
+ {
|
|
128
|
+ _context = context;
|
|
129
|
+ _mapper = mapper;
|
|
130
|
+ }
|
|
131
|
+
|
|
132
|
+ public async Task<TodosVm> Handler(GetTodosQuery request, CancellationToken cancellationToken)
|
|
133
|
+ {
|
|
134
|
+ return new TodosVm{
|
|
135
|
+ PriorityLevels = Enum.GetValues(typeof(PriorityLevel))
|
|
136
|
+ .Cast<PriorityLevel>()
|
|
137
|
+ .Select(p => new PriorityLevelDto{Value=(int)p, Name=p.ToString()})
|
|
138
|
+ .ToList,
|
|
139
|
+ Lists = await _context.TodosLists
|
|
140
|
+ .ProjectTo<TodoListDto>(_mapper.ConfigurationProvider)
|
|
141
|
+ .OrdreBy(t => t.Title)
|
|
142
|
+ .ToListAsync(cacnellationToken);
|
|
143
|
+ };
|
|
144
|
+ }
|
|
145
|
+}
|
|
146
|
+```
|
|
147
|
+
|
|
148
|
+在`MediatR`的请求管道中做验证。
|
|
149
|
+
|
|
150
|
+```
|
|
151
|
+public class RequestValidationBehavior<TRequest, TResponse> : IPiplelineBehavior<TRequest, TResponse> where TRequest : IRequest<TResponse>
|
|
152
|
+{
|
|
153
|
+ private readonly IENumerable<IValidator<TRequest>> _validators;
|
|
154
|
+
|
|
155
|
+ public RequestValidationBehavior(IEnumerable<IValidator<TRequest>> validators)
|
|
156
|
+ {
|
|
157
|
+ _validators = validators;
|
|
158
|
+ }
|
|
159
|
+
|
|
160
|
+ public Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
|
|
161
|
+ {
|
|
162
|
+ if(_validators.Any())
|
|
163
|
+ {
|
|
164
|
+ var context = new ValidationContext(request);
|
|
165
|
+
|
|
166
|
+ var failures = _validators
|
|
167
|
+ .Select(v => v.Validate(context))
|
|
168
|
+ .SelectMany(result => result.Errors)
|
|
169
|
+ .Whre(f => f != null)
|
|
170
|
+ .ToList();
|
|
171
|
+
|
|
172
|
+ if(failures.Count != 0)
|
|
173
|
+ {
|
|
174
|
+ throw new ValidationException(failures);
|
|
175
|
+ }
|
|
176
|
+ }
|
|
177
|
+ return next();
|
|
178
|
+ }
|
|
179
|
+}
|
|
180
|
+```
|
|
181
|
+
|
|
182
|
+在`MediatR`的请求管道中处理异常。
|
|
183
|
+
|
|
184
|
+```
|
|
185
|
+public class UnhandledExceptionBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
|
|
186
|
+{
|
|
187
|
+ private readonly ILogger<TRequest> _logger;
|
|
188
|
+
|
|
189
|
+ public UnhandledExceptionBehaviour(ILogger<TRequest> logger)
|
|
190
|
+ {
|
|
191
|
+ _logger = logger;
|
|
192
|
+ }
|
|
193
|
+
|
|
194
|
+ public async Task<TResponse> Handle(TRequest request, CancellationTOken canellationToken, RequestHandlerDelegate<TResponse> next)
|
|
195
|
+ {
|
|
196
|
+ try
|
|
197
|
+ {
|
|
198
|
+ return await next();
|
|
199
|
+ }
|
|
200
|
+ catch(Exception ex)
|
|
201
|
+ {
|
|
202
|
+ var requestName = typeof(TRequest).Name;
|
|
203
|
+ _logger.LogError();
|
|
204
|
+ throw;
|
|
205
|
+ }
|
|
206
|
+ }
|
|
207
|
+}
|
|
208
|
+```
|
|
209
|
+
|
|
210
|
+# 集成测试层
|
|
211
|
+
|
|
212
|
+引用`WebUI`层
|
|
213
|
+
|
|
214
|
+```
|
|
215
|
+dotnet add package FluentAssertions
|
|
216
|
+dotnet add package Moq
|
|
217
|
+dotnet add package Respawn
|
|
218
|
+```
|
|
219
|
+
|
|
220
|
+`GetTodosTests.cs`
|
|
221
|
+
|
|
222
|
+```
|
|
223
|
+
|
|
224
|
+using static Testing;
|
|
225
|
+public class GetTodosTests : TestBase //每次运行测试让数据库回到干净的状态
|
|
226
|
+{
|
|
227
|
+ [Test]
|
|
228
|
+ public async Task ShouldReturnAllListsAndAssociatedItems()
|
|
229
|
+ {
|
|
230
|
+ //Arrange
|
|
231
|
+ await AddAsync(new TodoList{
|
|
232
|
+ Title = "",
|
|
233
|
+ Items = {
|
|
234
|
+ new TodoItem {Title="",Done=true},
|
|
235
|
+ new TodoItem {Title="",Done=true},
|
|
236
|
+ new TodoItem {Title="",Done=true},
|
|
237
|
+ new TodoItem {Title=""},
|
|
238
|
+ new TodoItem {Title=""},
|
|
239
|
+ new TodoItem {Title=""}
|
|
240
|
+ }
|
|
241
|
+ });
|
|
242
|
+ var query = new GetTodosQuery();
|
|
243
|
+
|
|
244
|
+ //Act
|
|
245
|
+ TodosVm result = await SendAsync(query);
|
|
246
|
+
|
|
247
|
+ //Assert
|
|
248
|
+ result.Should().NotBeNull();
|
|
249
|
+ result.List.Should().HaveCount(1);
|
|
250
|
+ result.Lists.First().Items.Should().HaveCount();
|
|
251
|
+ }
|
|
252
|
+}
|
|
253
|
+```
|
|
254
|
+
|
|
255
|
+`CreateTodoListTests.cs`
|
|
256
|
+
|
|
257
|
+```
|
|
258
|
+
|
|
259
|
+using static Testing;
|
|
260
|
+public class CreateTodListTests : TestBase//每次运行测试让数据库回到干净的状态
|
|
261
|
+{
|
|
262
|
+ [Test]
|
|
263
|
+ public void ShouldRequredMinimumFileds()
|
|
264
|
+ {
|
|
265
|
+ var command = new CrateTodoListCommand();
|
|
266
|
+ FluenActions.Invoking(()=> SendAsync(command))
|
|
267
|
+ .Should().Throw<ValidaitonException>();
|
|
268
|
+ }
|
|
269
|
+
|
|
270
|
+ [Test]
|
|
271
|
+ public async Task ShouldRequiredUniqueTitle()
|
|
272
|
+ {
|
|
273
|
+ await SendAsync(new CreateTodoListCommand{
|
|
274
|
+ Title = ""
|
|
275
|
+ });
|
|
276
|
+
|
|
277
|
+ var command = new CreateTodoListCommand
|
|
278
|
+ {
|
|
279
|
+ Title = ""
|
|
280
|
+ };
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+ FluenActions.Invoking(() => SendAsync(comamnd))
|
|
284
|
+ .Should().Throw<ValidationException>();
|
|
285
|
+ }
|
|
286
|
+
|
|
287
|
+ [Test]
|
|
288
|
+ public async Task ShouldCreateTodoList()
|
|
289
|
+ {
|
|
290
|
+
|
|
291
|
+ var useId = await RunAsDefaultUserAsync();
|
|
292
|
+ var command = new CreateTodoListCommand
|
|
293
|
+ {
|
|
294
|
+ Title = ""
|
|
295
|
+ };
|
|
296
|
+
|
|
297
|
+ var listeId = await SendAsync(command);
|
|
298
|
+
|
|
299
|
+ var list = await FindAsync<TodoList>(listId);
|
|
300
|
+
|
|
301
|
+ list.Should().NotBuNull();
|
|
302
|
+ list.Title.Should().Be(command.Title);
|
|
303
|
+ list.Created.Should().BeCloseTo(DateTime.Now, 10000);
|
|
304
|
+ list.CreatedBy.Should().Be(userId);
|
|
305
|
+ }
|
|
306
|
+}
|
|
307
|
+```
|
|
308
|
+
|
|
309
|
+`UpdateDotListTests.cs`
|
|
310
|
+
|
|
311
|
+```
|
|
312
|
+using static Testing;
|
|
313
|
+public class UpdateTodoListTests : TestBase
|
|
314
|
+{
|
|
315
|
+ [Test]
|
|
316
|
+ public void ShouldRequireValidTodoListId()
|
|
317
|
+ {
|
|
318
|
+ var command = new UpdateTodoListCommand
|
|
319
|
+ {
|
|
320
|
+ Id = 99,
|
|
321
|
+ Title = "New Title"
|
|
322
|
+ };
|
|
323
|
+
|
|
324
|
+ FluenActions.Invoking(() => SendAsync(command)).Should().Throw<NotFoundException>();
|
|
325
|
+ }
|
|
326
|
+
|
|
327
|
+ [Test]
|
|
328
|
+ public async Task ShouldRequireUniqueTitle()
|
|
329
|
+ {
|
|
330
|
+ var listId = await SendAsync(new CreateTodoListCommand{Title=""});
|
|
331
|
+
|
|
332
|
+ await SendAsync(new CreateTodoListCommand={Title=""});
|
|
333
|
+ var command = new UpdateTodoListCommand
|
|
334
|
+ {
|
|
335
|
+ Id = listId,
|
|
336
|
+ Title = ""
|
|
337
|
+ };
|
|
338
|
+
|
|
339
|
+ FluentActions.Invoking(()=>
|
|
340
|
+ SendAsync(command)).Should().Throw<ValidationException>().Where(ex => ex.Errors.ContainsKey("Title"))
|
|
341
|
+ .And.Erros["Title"].Should().Contain("The specified title is already exists.");
|
|
342
|
+ }
|
|
343
|
+
|
|
344
|
+ [Test]
|
|
345
|
+ public async Task ShouldUpdateTodoList()
|
|
346
|
+ {
|
|
347
|
+ var userId = await RunAsDefaultUserAsync();
|
|
348
|
+ var listId = await SendAsync(new CreateTodoListCommand{
|
|
349
|
+ Title = ""
|
|
350
|
+ });
|
|
351
|
+
|
|
352
|
+ var command = new UpdateTodoListCommand
|
|
353
|
+ {
|
|
354
|
+ Id = listId,
|
|
355
|
+ Title= ""
|
|
356
|
+ };
|
|
357
|
+ await SendAsync(command);
|
|
358
|
+ var list =await FindAsync<TodoList>(listId);
|
|
359
|
+
|
|
360
|
+ list.Title.Should().Be(command.Title);
|
|
361
|
+ list.LastModifiedBy.Should().NotBeNull();
|
|
362
|
+ list.LastModifiedBy.Should().Be(userId);
|
|
363
|
+ list.LastModified.Should().NotBeNull();
|
|
364
|
+ list.LstModified.Should().BeCloaseTo(DateTime.Now, 1000);
|
|
365
|
+ }
|
|
366
|
+}
|
|
367
|
+```
|
|
368
|
+
|
|
369
|
+`Testing.cs`
|
|
370
|
+
|
|
371
|
+```
|
|
372
|
+[SetUpFixture]
|
|
373
|
+public class Testing
|
|
374
|
+{
|
|
375
|
+
|
|
376
|
+ private static IConfiguration _configuration;//配置
|
|
377
|
+ private static IServiceScopeFactory _scopeFactory;//域
|
|
378
|
+ private static Checkpoint _checkpoint;//Respawn
|
|
379
|
+ private static string _currentUserId;
|
|
380
|
+
|
|
381
|
+ [OneTimeSetUp]
|
|
382
|
+ public void RunBeforeAnyTests()
|
|
383
|
+ {
|
|
384
|
+ var buidler = new ConfigurationBuilder()
|
|
385
|
+ .SetBasePath(Directory.GetCurrentDirectory)
|
|
386
|
+ .AddJsonFile("appsettings.json", true, true)
|
|
387
|
+ .AddEnvironmentVariables();
|
|
388
|
+
|
|
389
|
+ _configuration = builder.Build();
|
|
390
|
+
|
|
391
|
+ var services = new ServiceCollection();//看作是容器
|
|
392
|
+ var startup = new Startup(_configuration);//Startup.cs需要IConfiguration
|
|
393
|
+
|
|
394
|
+ //ServiceCollection需要宿主
|
|
395
|
+ services.AddSignleton(Mock.Of<IWebHostEnvironment>(w =>
|
|
396
|
+ w.ApplcationName == "CleanTesting.WebUI" &&
|
|
397
|
+ w.EnvirnmentName == "Development"));
|
|
398
|
+
|
|
399
|
+ startup.ConfigureServices(services);
|
|
400
|
+
|
|
401
|
+ //Replace service registration for ICurrentUserService
|
|
402
|
+ //Remove existing registration
|
|
403
|
+ var currentUserServiceDescriptor = services.FirstOrDefault(d => d.ServiceType == typeof(ICurrentUserService));
|
|
404
|
+ service.Remove(currentUserServiceDescriptor);
|
|
405
|
+
|
|
406
|
+ //Register testing version
|
|
407
|
+ services.AddTransient(provider =>
|
|
408
|
+ Mock.Of<ICurrentUserService>(s => s.UserId == _currentUserId));
|
|
409
|
+
|
|
410
|
+ _scopeFactory = services.BuilderServiceProvider().GetService<IServiceScopeFactory>();
|
|
411
|
+
|
|
412
|
+ _checkpoint = new Checkpoint{
|
|
413
|
+ TablesToIgnore = new [] {"__EFMigrationsHistory"}
|
|
414
|
+ };
|
|
415
|
+ }
|
|
416
|
+
|
|
417
|
+ public static async Task<string> RunAsDefaultUserAsync()
|
|
418
|
+ {
|
|
419
|
+ return await RundAsUserAsync("","");
|
|
420
|
+ _currentUserId = null;
|
|
421
|
+ }
|
|
422
|
+
|
|
423
|
+ public static async Task<string> RunAsUserAsync(string userName, string password)
|
|
424
|
+ {
|
|
425
|
+ using var scope = _scopeFactory.CreateScope();
|
|
426
|
+ var userManager = scope.ServiceProvider.GetService<UserManager<ApplicaitonUser>>();
|
|
427
|
+
|
|
428
|
+ var user = new ApplicationUser{UserName=userName, Email = userName};
|
|
429
|
+ var result = await userManager.CreateAsync(user, password);
|
|
430
|
+ _currentUserId = user.Id;
|
|
431
|
+ return _currentUserId;
|
|
432
|
+ }
|
|
433
|
+
|
|
434
|
+ public static async Task ResetState()
|
|
435
|
+ {
|
|
436
|
+ await _checkpoint.Reset(_configuration.GetConnectionString("DefaultConnection"));
|
|
437
|
+ }
|
|
438
|
+
|
|
439
|
+ public static async Task AddAsync<TEntity>(TEntity entity) where TEntity : class
|
|
440
|
+ {
|
|
441
|
+ using var scope = _scopeFactory.CreateScope();
|
|
442
|
+ var context = scope.ServiceProvider.GetService<ApplicationDbContext>();
|
|
443
|
+ context.Add(entity);
|
|
444
|
+ await context.SaveChangesAsync();
|
|
445
|
+ }
|
|
446
|
+
|
|
447
|
+ public static async Task<TResponse> SendAsync<TResponse>(IRequest<TResponse> request)
|
|
448
|
+ {
|
|
449
|
+ using var scope = _scopeFacotry.CreateScope();
|
|
450
|
+ var mediator = scope.ServiceProvider.GetService<IMediator>();
|
|
451
|
+ return await mediator.Send(request);
|
|
452
|
+ }
|
|
453
|
+
|
|
454
|
+ public static async Task<TEntity> FindAsync<TEntity>(int id)
|
|
455
|
+ {
|
|
456
|
+ using var scope = _scopeFactory.CreateScope();
|
|
457
|
+ var context = scope.ServiceProvider.GetService<ApplicationContext>();
|
|
458
|
+ return await context.FindAsync<TEntity>(id);
|
|
459
|
+ }
|
|
460
|
+}
|
|
461
|
+```
|
|
462
|
+
|
|
463
|
+`appSetting.json`
|
|
464
|
+
|
|
465
|
+```
|
|
466
|
+{
|
|
467
|
+ "UseInMemoryDatabase":false,
|
|
468
|
+ "ConnectionStrings":{
|
|
469
|
+ "DefaultConnection" : "Server=(localdb)\\mssqllocaldb;Database=CleanTestingDb;Truested_Connection=True;MultipleActiveRestultSet"
|
|
470
|
+ },
|
|
471
|
+ "IdentityServer":{
|
|
472
|
+ "Clients":{
|
|
473
|
+ "CleanTesting.WebUI": {
|
|
474
|
+ "Profile": "IdentityServerSPA"
|
|
475
|
+ }
|
|
476
|
+ },
|
|
477
|
+ "Key":{
|
|
478
|
+ "Type" : "Development"
|
|
479
|
+ }
|
|
480
|
+ }
|
|
481
|
+}
|
|
482
|
+```
|
|
483
|
+
|
|
484
|
+`TestBase.cs`
|
|
485
|
+
|
|
486
|
+```
|
|
487
|
+using static Testing;
|
|
488
|
+public calss TestBase
|
|
489
|
+{
|
|
490
|
+ [SetUp]
|
|
491
|
+ public async Task SetUp()
|
|
492
|
+ {
|
|
493
|
+ await ResetState();
|
|
494
|
+ }
|
|
495
|
+}
|
|
496
|
+```
|
|
497
|
+
|
|
498
|
+# 资源
|
|
499
|
+
|
|
500
|
+- `Clean Testing Sample Code`: `https://github.com/jasontaylordev/cleantesting`
|
|
501
|
+- `Rules to Better Unit Tests`: `https://rules.ssw.com.au/rules-to-better-unit-tests`(翻墙)
|
|
502
|
+- `Fixie Demo`: `https://github.com/fixie/fixie.demo`
|