-
-
Notifications
You must be signed in to change notification settings - Fork 128
Expand file tree
/
Copy pathRealWorldScenarioTests.cs
More file actions
613 lines (493 loc) · 22.6 KB
/
Copy pathRealWorldScenarioTests.cs
File metadata and controls
613 lines (493 loc) · 22.6 KB
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
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
using TUnit.Mocks;
using TUnit.Mocks.Arguments;
using TUnit.Mocks.Exceptions;
namespace TUnit.Mocks.Tests;
// ───────────────────────────────────────────────────────────────
// Supporting DTOs
// ───────────────────────────────────────────────────────────────
public class UserDto
{
public int Id { get; set; }
public string Name { get; set; } = "";
public string Email { get; set; } = "";
}
public class OrderDto
{
public int OrderId { get; set; }
public string ItemName { get; set; } = "";
public decimal Price { get; set; }
}
// ───────────────────────────────────────────────────────────────
// 1. Service Layer Pattern — Repository + Unit of Work
// ───────────────────────────────────────────────────────────────
public interface IUserRepository
{
Task<UserDto?> GetByIdAsync(int id);
Task<IReadOnlyList<UserDto>> GetAllAsync();
Task<UserDto> CreateAsync(UserDto user);
Task UpdateAsync(UserDto user);
Task DeleteAsync(int id);
Task<bool> ExistsAsync(int id);
Task<IReadOnlyList<UserDto>> FindByNameAsync(string name, CancellationToken cancellationToken = default);
}
public interface IUnitOfWork : IDisposable
{
Task SaveChangesAsync(CancellationToken cancellationToken = default);
Task<ITransaction> BeginTransactionAsync();
}
public interface ITransaction : IDisposable, IAsyncDisposable
{
Task CommitAsync();
Task RollbackAsync();
}
// ───────────────────────────────────────────────────────────────
// 2. Multi-Interface Service
// ───────────────────────────────────────────────────────────────
public interface ILogger
{
void Log(string level, string message);
void Log(string level, string message, Exception? exception);
}
public interface INotificationService
{
Task SendEmailAsync(string to, string subject, string body);
Task<bool> SendSmsAsync(string phoneNumber, string message);
}
public interface ICache
{
T? Get<T>(string key) where T : class;
void Set<T>(string key, T value, TimeSpan? expiry = null) where T : class;
bool Remove(string key);
bool Exists(string key);
}
// ───────────────────────────────────────────────────────────────
// 3. Complex Return Types
// ───────────────────────────────────────────────────────────────
public interface IAnalyticsService
{
Task<Dictionary<string, List<decimal>>> GetMetricsAsync(string category);
(bool Success, string? ErrorMessage) Validate(string input);
Task<IReadOnlyDictionary<int, string>> GetLookupAsync();
}
// ───────────────────────────────────────────────────────────────
// 5. Nullable Reference Types
// ───────────────────────────────────────────────────────────────
public interface INullableService
{
string? GetNullableString(int id);
Task<UserDto?> FindUserAsync(string? name);
void Process(string? input, int? count);
}
// ───────────────────────────────────────────────────────────────
// 4. Dependency Injection Integration — Real Service
// ───────────────────────────────────────────────────────────────
public class OrderService
{
private readonly IUserRepository _userRepo;
private readonly INotificationService _notifications;
private readonly ILogger _logger;
public OrderService(IUserRepository userRepo, INotificationService notifications, ILogger logger)
{
_userRepo = userRepo;
_notifications = notifications;
_logger = logger;
}
public async Task<bool> PlaceOrderAsync(int userId, string itemName)
{
var user = await _userRepo.GetByIdAsync(userId);
if (user == null)
{
_logger.Log("Warning", $"User {userId} not found");
return false;
}
await _notifications.SendEmailAsync(user.Email, "Order Placed", $"Your order for {itemName} has been placed.");
_logger.Log("Info", $"Order placed for user {userId}");
return true;
}
}
// ═══════════════════════════════════════════════════════════════
// Test Class
// ═══════════════════════════════════════════════════════════════
/// <summary>
/// Real-world mocking scenario tests that exercise complex patterns
/// commonly found in production codebases: repository/UoW, DI orchestration,
/// multi-interface coordination, complex return types, and nullable handling.
/// </summary>
public class RealWorldScenarioTests
{
// ───────────────────────────────────────────────────────────
// 1. Service Layer Pattern
// ───────────────────────────────────────────────────────────
[Test]
public async Task Repository_CRUD_Full_Lifecycle()
{
// Arrange
var mock = IUserRepository.Mock();
var user = new UserDto { Id = 1, Name = "Alice", Email = "alice@example.com" };
mock.CreateAsync(Any()).Returns(user);
mock.GetByIdAsync(1).Returns(user);
mock.ExistsAsync(1).Returns(true);
IUserRepository repo = mock.Object;
// Act — Create
var created = await repo.CreateAsync(user);
await Assert.That(created.Name).IsEqualTo("Alice");
// Act — Read back
var fetched = await repo.GetByIdAsync(1);
await Assert.That(fetched).IsNotNull();
await Assert.That(fetched!.Email).IsEqualTo("alice@example.com");
// Act — Update (void Task, just call it)
var updatedUser = new UserDto { Id = 1, Name = "Alice Updated", Email = "alice@example.com" };
await repo.UpdateAsync(updatedUser);
// Act — Exists
var exists = await repo.ExistsAsync(1);
await Assert.That(exists).IsTrue();
// Verify all calls
mock.CreateAsync(Any()).WasCalled(Times.Once);
mock.GetByIdAsync(1).WasCalled(Times.Once);
mock.UpdateAsync(Any()).WasCalled(Times.Once);
mock.ExistsAsync(1).WasCalled(Times.Once);
}
[Test]
public async Task Repository_With_CancellationToken_Default_Parameter()
{
// Arrange
var mock = IUserRepository.Mock();
var users = new List<UserDto>
{
new() { Id = 1, Name = "Alice Smith", Email = "alice@example.com" },
new() { Id = 2, Name = "Alice Jones", Email = "alicej@example.com" },
};
mock.FindByNameAsync("Alice", Any())
.Returns((IReadOnlyList<UserDto>)users);
IUserRepository repo = mock.Object;
// Act — call without CancellationToken (uses default)
var result = await repo.FindByNameAsync("Alice");
// Assert
await Assert.That(result).Count().IsEqualTo(2);
await Assert.That(result[0].Name).IsEqualTo("Alice Smith");
// Verify
mock.FindByNameAsync("Alice", Any()).WasCalled(Times.Once);
}
[Test]
public async Task UnitOfWork_Transaction_Commit_Flow()
{
// Arrange
var mockTx = ITransaction.Mock();
var mockUow = IUnitOfWork.Mock();
mockUow.BeginTransactionAsync().Returns(mockTx.Object);
IUnitOfWork uow = mockUow.Object;
// Act — simulate a transactional operation
var tx = await uow.BeginTransactionAsync();
await uow.SaveChangesAsync();
await tx.CommitAsync();
// Assert
mockUow.BeginTransactionAsync().WasCalled(Times.Once);
mockUow.SaveChangesAsync(Any()).WasCalled(Times.Once);
mockTx.CommitAsync().WasCalled(Times.Once);
mockTx.RollbackAsync().WasNeverCalled();
}
[Test]
public async Task UnitOfWork_Transaction_Rollback_On_Exception()
{
// Arrange
var mockTx = ITransaction.Mock();
var mockUow = IUnitOfWork.Mock();
mockUow.BeginTransactionAsync().Returns(mockTx.Object);
mockUow.SaveChangesAsync(Any())
.Throws<InvalidOperationException>();
IUnitOfWork uow = mockUow.Object;
// Act — simulate a transactional operation that fails
var tx = await uow.BeginTransactionAsync();
try
{
await uow.SaveChangesAsync();
}
catch (InvalidOperationException)
{
await tx.RollbackAsync();
}
// Assert — rollback was called, commit was not
mockTx.RollbackAsync().WasCalled(Times.Once);
mockTx.CommitAsync().WasNeverCalled();
}
[Test]
public async Task Repository_Returns_Null_For_NotFound()
{
// Arrange
var mock = IUserRepository.Mock();
mock.GetByIdAsync(999).Returns((UserDto?)null);
IUserRepository repo = mock.Object;
// Act
var result = await repo.GetByIdAsync(999);
// Assert
await Assert.That(result).IsNull();
}
// ───────────────────────────────────────────────────────────
// 2. Multi-Interface Service
// ───────────────────────────────────────────────────────────
[Test]
public async Task Multiple_Mocks_Injected_Into_Service_Orchestration()
{
// Arrange — create 3 mocks that a hypothetical service would depend on
var mockRepo = IUserRepository.Mock();
var mockNotify = INotificationService.Mock();
var mockLogger = ILogger.Mock();
var user = new UserDto { Id = 1, Name = "Bob", Email = "bob@example.com" };
mockRepo.GetByIdAsync(1).Returns(user);
// Act — orchestrate the mocks together as a service would
IUserRepository repo = mockRepo.Object;
INotificationService notify = mockNotify.Object;
ILogger logger = mockLogger.Object;
var fetchedUser = await repo.GetByIdAsync(1);
await Assert.That(fetchedUser).IsNotNull();
await notify.SendEmailAsync(fetchedUser!.Email, "Welcome", "Hello Bob!");
logger.Log("Info", "Welcome email sent");
// Verify all three mocks
mockRepo.GetByIdAsync(1).WasCalled(Times.Once);
mockNotify.SendEmailAsync("bob@example.com", "Welcome", "Hello Bob!").WasCalled(Times.Once);
mockLogger.Log("Info", "Welcome email sent").WasCalled(Times.Once);
}
[Test]
public async Task Logger_Method_Overloads_Distinct_Setups()
{
// Arrange
var mock = ILogger.Mock();
var twoArgCallCount = 0;
var threeArgCallCount = 0;
mock.Log(Any(), Any())
.Callback(() => twoArgCallCount++);
mock.Log(Any(), Any(), Any<Exception?>())
.Callback(() => threeArgCallCount++);
ILogger logger = mock.Object;
// Act — call each overload
logger.Log("Info", "simple message");
logger.Log("Error", "something failed", new InvalidOperationException("boom"));
// Assert — each overload was tracked independently
await Assert.That(twoArgCallCount).IsEqualTo(1);
await Assert.That(threeArgCallCount).IsEqualTo(1);
// Verify
mock.Log(Any(), Any()).WasCalled(Times.Once);
mock.Log(Any(), Any(), Any<Exception?>()).WasCalled(Times.Once);
}
[Test]
public async Task Cache_Generic_Methods_With_Different_Types()
{
// Arrange
var mock = ICache.Mock();
var user = new UserDto { Id = 1, Name = "Alice", Email = "alice@example.com" };
var order = new OrderDto { OrderId = 42, ItemName = "Widget", Price = 9.99m };
mock.Get<UserDto>("user:1").Returns(user);
mock.Get<OrderDto>("order:42").Returns(order);
ICache cache = mock.Object;
// Act
var cachedUser = cache.Get<UserDto>("user:1");
var cachedOrder = cache.Get<OrderDto>("order:42");
// Assert — different generic types return different values
await Assert.That(cachedUser).IsNotNull();
await Assert.That(cachedUser!.Name).IsEqualTo("Alice");
await Assert.That(cachedOrder).IsNotNull();
await Assert.That(cachedOrder!.OrderId).IsEqualTo(42);
// Unconfigured key returns null
var missing = cache.Get<UserDto>("user:999");
await Assert.That(missing).IsNull();
}
[Test]
public async Task Notification_Conditional_Send()
{
// Arrange — SendSmsAsync returns true for one number, false for another
var mock = INotificationService.Mock();
mock.SendSmsAsync("+1234567890", Any()).Returns(true);
mock.SendSmsAsync("+0000000000", Any()).Returns(false);
INotificationService notify = mock.Object;
// Act
var successResult = await notify.SendSmsAsync("+1234567890", "Hello!");
var failResult = await notify.SendSmsAsync("+0000000000", "Hello!");
// Assert
await Assert.That(successResult).IsTrue();
await Assert.That(failResult).IsFalse();
}
// ───────────────────────────────────────────────────────────
// 3. Complex Return Types
// ───────────────────────────────────────────────────────────
[Test]
public async Task Complex_Dictionary_Return_Type()
{
// Arrange
var mock = IAnalyticsService.Mock();
var metrics = new Dictionary<string, List<decimal>>
{
["revenue"] = [100.50m, 200.75m, 300.00m],
["costs"] = [50.25m, 75.00m],
};
mock.GetMetricsAsync("finance").Returns(metrics);
IAnalyticsService analytics = mock.Object;
// Act
var result = await analytics.GetMetricsAsync("finance");
// Assert
await Assert.That(result).IsNotNull();
await Assert.That(result.ContainsKey("revenue")).IsTrue();
await Assert.That(result["revenue"]).Count().IsEqualTo(3);
await Assert.That(result["revenue"][0]).IsEqualTo(100.50m);
await Assert.That(result["costs"]).Count().IsEqualTo(2);
}
[Test]
public async Task Tuple_Return_Type()
{
// Arrange
var mock = IAnalyticsService.Mock();
mock.Validate("good-input").Returns((true, (string?)null));
mock.Validate("bad-input").Returns((false, (string?)"Invalid format"));
IAnalyticsService analytics = mock.Object;
// Act
var goodResult = analytics.Validate("good-input");
var badResult = analytics.Validate("bad-input");
// Assert
await Assert.That(goodResult.Success).IsTrue();
await Assert.That(goodResult.ErrorMessage).IsNull();
await Assert.That(badResult.Success).IsFalse();
await Assert.That(badResult.ErrorMessage).IsEqualTo("Invalid format");
}
[Test]
public async Task ReadOnlyDictionary_Return()
{
// Arrange
var mock = IAnalyticsService.Mock();
var lookup = new Dictionary<int, string>
{
[1] = "Active",
[2] = "Inactive",
[3] = "Pending",
};
mock.GetLookupAsync()
.Returns((IReadOnlyDictionary<int, string>)lookup);
IAnalyticsService analytics = mock.Object;
// Act
var result = await analytics.GetLookupAsync();
// Assert
await Assert.That(result).IsNotNull();
await Assert.That(result.Count).IsEqualTo(3);
await Assert.That(result[1]).IsEqualTo("Active");
await Assert.That(result[2]).IsEqualTo("Inactive");
await Assert.That(result[3]).IsEqualTo("Pending");
}
// ───────────────────────────────────────────────────────────
// 4. Dependency Injection Integration Pattern
// ───────────────────────────────────────────────────────────
[Test]
public async Task DI_Integration_Happy_Path()
{
// Arrange
var mockRepo = IUserRepository.Mock();
var mockNotify = INotificationService.Mock();
var mockLogger = ILogger.Mock();
var user = new UserDto { Id = 1, Name = "Alice", Email = "alice@example.com" };
mockRepo.GetByIdAsync(1).Returns(user);
var service = new OrderService(mockRepo.Object, mockNotify.Object, mockLogger.Object);
// Act
var result = await service.PlaceOrderAsync(1, "Widget");
// Assert
await Assert.That(result).IsTrue();
// Verify the repo was queried
mockRepo.GetByIdAsync(1).WasCalled(Times.Once);
// Verify email was sent to the correct address
mockNotify.SendEmailAsync(
"alice@example.com",
"Order Placed",
"Your order for Widget has been placed."
).WasCalled(Times.Once);
// Verify info was logged
mockLogger.Log("Info", "Order placed for user 1").WasCalled(Times.Once);
}
[Test]
public async Task DI_Integration_User_Not_Found()
{
// Arrange
var mockRepo = IUserRepository.Mock();
var mockNotify = INotificationService.Mock();
var mockLogger = ILogger.Mock();
mockRepo.GetByIdAsync(999).Returns((UserDto?)null);
var service = new OrderService(mockRepo.Object, mockNotify.Object, mockLogger.Object);
// Act
var result = await service.PlaceOrderAsync(999, "Widget");
// Assert — returns false
await Assert.That(result).IsFalse();
// Verify warning was logged
mockLogger.Log("Warning", "User 999 not found").WasCalled(Times.Once);
// Verify email was NEVER sent
mockNotify.SendEmailAsync(
Any(), Any(), Any()
).WasNeverCalled();
}
[Test]
public async Task DI_Integration_Verify_Exact_Email_Content()
{
// Arrange
var mockRepo = IUserRepository.Mock();
var mockNotify = INotificationService.Mock();
var mockLogger = ILogger.Mock();
var bodyArg = Any<string>();
var user = new UserDto { Id = 7, Name = "Charlie", Email = "charlie@example.com" };
mockRepo.GetByIdAsync(7).Returns(user);
// SendEmailAsync returns Task (void-async), so use Callback to capture args
mockNotify.SendEmailAsync(
Any(), Any(), bodyArg
).Callback(() => { });
var service = new OrderService(mockRepo.Object, mockNotify.Object, mockLogger.Object);
// Act
await service.PlaceOrderAsync(7, "Gadget");
// Assert — verify the captured email body content
await Assert.That(bodyArg.Values).Count().IsEqualTo(1);
await Assert.That(bodyArg.Latest).IsEqualTo("Your order for Gadget has been placed.");
}
// ───────────────────────────────────────────────────────────
// 5. Nullable Reference Types
// ───────────────────────────────────────────────────────────
[Test]
public async Task Nullable_String_Return_Configured_Null()
{
// Arrange
var mock = INullableService.Mock();
mock.GetNullableString(1).Returns((string?)null);
INullableService svc = mock.Object;
// Act
var result = svc.GetNullableString(1);
// Assert
await Assert.That(result).IsNull();
}
[Test]
public async Task Nullable_Parameter_Matching()
{
// Arrange
var mock = INullableService.Mock();
var callCount = 0;
mock.Process(IsNull<string>(), Any<int?>())
.Callback(() => callCount++);
mock.Process(IsNotNull<string>(), Any<int?>())
.Callback(() => callCount += 10);
INullableService svc = mock.Object;
// Act — call with null input
svc.Process(null, 5);
// Act — call with non-null input
svc.Process("hello", null);
// Assert — null path: +1, non-null path: +10
await Assert.That(callCount).IsEqualTo(11);
}
[Test]
public async Task Nullable_Async_Return()
{
// Arrange
var mock = INullableService.Mock();
mock.FindUserAsync(Any<string?>()).Returns((UserDto?)null);
INullableService svc = mock.Object;
// Act
var result = await svc.FindUserAsync("nonexistent");
// Assert
await Assert.That(result).IsNull();
// Now configure to return a user for a specific name
mock.FindUserAsync("Alice")
.Returns((UserDto?)new UserDto { Id = 1, Name = "Alice", Email = "alice@example.com" });
var found = await svc.FindUserAsync("Alice");
await Assert.That(found).IsNotNull();
await Assert.That(found!.Name).IsEqualTo("Alice");
}
}