/
EventAssertionSpecs.cs
1065 lines (869 loc) · 39.6 KB
/
EventAssertionSpecs.cs
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
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#if NETFRAMEWORK
using System.Reflection;
using System.Reflection.Emit;
#endif
using System;
using System.ComponentModel;
using System.Linq;
using FluentAssertions.Events;
using FluentAssertions.Extensions;
using FluentAssertions.Formatting;
using Xunit;
using Xunit.Sdk;
namespace FluentAssertions.Specs.Events
{
[Collection("EventMonitoring")]
public class EventAssertionSpecs
{
public class ShouldRaise
{
[Fact]
public void When_asserting_an_event_that_doesnt_exist_it_should_throw()
{
// Arrange
var subject = new EventRaisingClass();
using var monitoredSubject = subject.Monitor();
// Act
// ReSharper disable once AccessToDisposedClosure
Action act = () => monitoredSubject.Should().Raise("NonExistingEvent");
// Assert
act.Should().Throw<InvalidOperationException>().WithMessage(
"Not monitoring any events named \"NonExistingEvent\".");
}
[Fact]
public void When_asserting_that_an_event_was_not_raised_and_it_doesnt_exist_it_should_throw()
{
// Arrange
var subject = new EventRaisingClass();
using var monitor = subject.Monitor();
// Act
Action act = () => monitor.Should().NotRaise("NonExistingEvent");
// Assert
act.Should().Throw<InvalidOperationException>().WithMessage(
"Not monitoring any events named \"NonExistingEvent\".");
}
[Fact]
public void When_an_event_was_not_raised_it_should_throw_and_use_the_reason()
{
// Arrange
var subject = new EventRaisingClass();
using var monitor = subject.Monitor();
// Act
Action act = () => monitor.Should().Raise("PropertyChanged", "{0} should cause the event to get raised", "Foo()");
// Assert
act.Should().Throw<XunitException>().WithMessage(
"Expected object " + Formatter.ToString(subject) +
" to raise event \"PropertyChanged\" because Foo() should cause the event to get raised, but it did not.");
}
[Fact]
public void When_the_expected_event_was_raised_it_should_not_throw()
{
// Arrange
var subject = new EventRaisingClass();
using var monitor = subject.Monitor();
subject.RaiseEventWithoutSender();
// Act
Action act = () => monitor.Should().Raise("PropertyChanged");
// Assert
act.Should().NotThrow();
}
[Fact]
public void When_an_unexpected_event_was_raised_it_should_throw_and_use_the_reason()
{
// Arrange
var subject = new EventRaisingClass();
using var monitor = subject.Monitor();
subject.RaiseEventWithoutSender();
// Act
Action act = () =>
monitor.Should().NotRaise("PropertyChanged", "{0} should cause the event to get raised", "Foo()");
// Assert
act.Should().Throw<XunitException>()
.WithMessage("Expected object " + Formatter.ToString(subject) +
" to not raise event \"PropertyChanged\" because Foo() should cause the event to get raised, but it did.");
}
[Fact]
public void When_an_unexpected_event_was_not_raised_it_should_not_throw()
{
// Arrange
var subject = new EventRaisingClass();
using var monitor = subject.Monitor();
// Act
Action act = () => monitor.Should().NotRaise("PropertyChanged");
// Assert
act.Should().NotThrow();
}
[Fact]
public void When_the_event_sender_is_not_the_expected_object_it_should_throw()
{
// Arrange
var subject = new EventRaisingClass();
using var monitor = subject.Monitor();
subject.RaiseEventWithoutSender();
// Act
Action act = () => monitor.Should().Raise("PropertyChanged").WithSender(subject);
// Assert
act.Should().Throw<XunitException>()
.WithMessage($"Expected sender {Formatter.ToString(subject)}, but found {{<null>}}.");
}
[Fact]
public void When_the_event_sender_is_the_expected_object_it_should_not_throw()
{
// Arrange
var subject = new EventRaisingClass();
using var monitor = subject.Monitor();
subject.RaiseEventWithSender();
// Act
Action act = () => monitor.Should().Raise("PropertyChanged").WithSender(subject);
// Assert
act.Should().NotThrow();
}
[Fact]
public void When_injecting_a_null_predicate_into_WithArgs_it_should_throw()
{
// Arrange
var subject = new EventRaisingClass();
using var monitor = subject.Monitor();
subject.RaiseNonConventionalEvent("first argument", 2, "third argument");
// Act
Action act = () => monitor.Should()
.Raise("NonConventionalEvent")
.WithArgs<string>(predicate: null);
// Assert
act.Should().ThrowExactly<ArgumentNullException>()
.WithParameterName("predicate");
}
[Fact]
public void When_the_event_parameters_dont_match_it_should_throw()
{
// Arrange
var subject = new EventRaisingClass();
using var monitor = subject.Monitor();
subject.RaiseEventWithoutSender();
// Act
Action act = () => monitor
.Should().Raise("PropertyChanged")
.WithArgs<PropertyChangedEventArgs>(args => args.PropertyName == "SomeProperty");
// Assert
act
.Should().Throw<XunitException>()
.WithMessage(
"Expected at least one event which arguments are of type*PropertyChangedEventArgs*matches*(args.PropertyName == \"SomeProperty\"), but found none.");
}
[Fact]
public void When_the_event_args_are_of_a_different_type_it_should_throw()
{
// Arrange
var subject = new EventRaisingClass();
using var monitor = subject.Monitor();
subject.RaiseEventWithSenderAndPropertyName("SomeProperty");
// Act
Action act = () => monitor
.Should().Raise("PropertyChanged")
.WithArgs<CancelEventArgs>(args => args.Cancel);
// Assert
act
.Should().Throw<XunitException>()
.WithMessage("Expected*event*argument*type*CancelEventArgs>*");
}
[Fact]
public void When_the_event_parameters_do_match_it_should_not_throw()
{
// Arrange
var subject = new EventRaisingClass();
using var monitor = subject.Monitor();
subject.RaiseEventWithSenderAndPropertyName("SomeProperty");
// Act
Action act = () => monitor
.Should().Raise("PropertyChanged")
.WithArgs<PropertyChangedEventArgs>(args => args.PropertyName == "SomeProperty");
// Assert
act.Should().NotThrow();
}
[Fact]
public void When_running_in_parallel_it_should_not_throw()
{
// Arrange
void Action(int _)
{
EventRaisingClass subject = new EventRaisingClass();
using var monitor = subject.Monitor();
subject.RaiseEventWithSender();
monitor.Should().Raise("PropertyChanged");
}
// Act
Action act = () => Enumerable.Range(0, 1000)
.AsParallel()
.ForAll(Action);
// Assert
act.Should().NotThrow();
}
[Fact]
public void When_a_monitored_class_event_has_fired_it_should_be_possible_to_reset_the_event_monitor()
{
// Arrange
var subject = new EventRaisingClass();
using var eventMonitor = subject.Monitor();
subject.RaiseEventWithSenderAndPropertyName("SomeProperty");
// Act
eventMonitor.Clear();
// Assert
eventMonitor.Should().NotRaise("PropertyChanged");
}
[Fact]
public void When_a_non_conventional_event_with_a_specific_argument_was_raised_it_should_not_throw()
{
// Arrange
var subject = new EventRaisingClass();
using var monitor = subject.Monitor();
subject.RaiseNonConventionalEvent("first argument", 2, "third argument");
// Act
Action act = () => monitor
.Should().Raise("NonConventionalEvent")
.WithArgs<string>(args => args == "third argument");
// Assert
act.Should().NotThrow();
}
[Fact]
public void When_a_non_conventional_event_with_many_specific_arguments_was_raised_it_should_not_throw()
{
// Arrange
var subject = new EventRaisingClass();
using var monitor = subject.Monitor();
subject.RaiseNonConventionalEvent("first argument", 2, "third argument");
// Act
Action act = () => monitor
.Should().Raise("NonConventionalEvent")
.WithArgs<string>(null, args => args == "third argument");
// Assert
act.Should().NotThrow();
}
[Fact]
public void When_a_predicate_based_parameter_assertion_expects_more_parameters_then_an_event_has_it_should_throw()
{
// Arrange
var subject = new EventRaisingClass();
using var monitor = subject.Monitor();
subject.RaiseNonConventionalEvent("first argument", 2, "third argument");
// Act
Action act = () => monitor
.Should().Raise(nameof(EventRaisingClass.NonConventionalEvent))
.WithArgs<string>(null, null, null, args => args == "fourth argument");
// Assert
act.Should().Throw<ArgumentException>().WithMessage("*4 parameters*String*, but*2*");
}
[Fact]
public void When_a_non_conventional_event_with_a_specific_argument_was_not_raised_it_should_throw()
{
// Arrange
const int wrongArgument = 3;
var subject = new EventRaisingClass();
using var monitor = subject.Monitor();
subject.RaiseNonConventionalEvent("first argument", 2, "third argument");
// Act
Action act = () => monitor
.Should().Raise("NonConventionalEvent")
.WithArgs<int>(args => args == wrongArgument);
// Assert
act.Should().Throw<XunitException>().WithMessage(
"Expected at least one event which arguments*type*Int32*matches*(args == " + wrongArgument + "), but found none.");
}
[Fact]
public void When_a_non_conventional_event_with_many_specific_arguments_was_not_raised_it_should_throw()
{
// Arrange
const string wrongArgument = "not a third argument";
var subject = new EventRaisingClass();
using var monitor = subject.Monitor();
subject.RaiseNonConventionalEvent("first argument", 2, "third argument");
// Act
Action act = () => monitor
.Should().Raise("NonConventionalEvent")
.WithArgs<string>(null, args => args == wrongArgument);
// Assert
act.Should().Throw<XunitException>().WithMessage(
"Expected at least one event which arguments*matches*\"(args == \"" + wrongArgument +
"\")\", but found none.");
}
[Fact]
public void When_a_specific_event_is_expected_it_should_return_only_relevant_events()
{
// Arrange
var observable = new EventRaisingClass();
using var monitor = observable.Monitor();
// Act
observable.RaiseEventWithSpecificSender("Foo");
observable.RaiseEventWithSpecificSender("Bar");
observable.RaiseNonConventionalEvent("don't care", 123, "don't care");
// Assert
var recording = monitor
.Should()
.Raise(nameof(observable.PropertyChanged));
recording.EventName.Should().Be(nameof(observable.PropertyChanged));
recording.EventObject.Should().BeSameAs(observable);
recording.EventHandlerType.Should().Be(typeof(PropertyChangedEventHandler));
recording.Should().HaveCount(2, "because only two property changed events were raised");
}
[Fact]
public void When_a_specific_sender_is_expected_it_should_return_only_relevant_events()
{
// Arrange
var observable = new EventRaisingClass();
using var monitor = observable.Monitor();
// Act
observable.RaiseEventWithSpecificSender(observable);
observable.RaiseEventWithSpecificSender(new object());
// Assert
var recording = monitor
.Should()
.Raise(nameof(observable.PropertyChanged))
.WithSender(observable);
recording.Should().ContainSingle().Which.Parameters.First().Should().BeSameAs(observable);
}
[Fact]
public void When_constraints_are_specified_it_should_filter_the_events_based_on_those_constraints()
{
// Arrange
var observable = new EventRaisingClass();
using var monitor = observable.Monitor();
// Act
observable.RaiseEventWithSenderAndPropertyName("Foo");
observable.RaiseEventWithSenderAndPropertyName("Boo");
// Assert
var recording = monitor
.Should()
.Raise(nameof(observable.PropertyChanged))
.WithSender(observable)
.WithArgs<PropertyChangedEventArgs>(args => args.PropertyName == "Boo");
recording
.Should().ContainSingle("because we were expecting a specific property change")
.Which.Parameters.Last().Should().BeOfType<PropertyChangedEventArgs>()
.Which.PropertyName.Should().Be("Boo");
}
[Fact]
public void When_events_are_raised_regardless_of_time_tick_it_should_return_by_invokation_order()
{
// Arrange
var observable = new TestEventRaisingInOrder();
var utcNow = 11.January(2022).At(12, 00).AsUtc();
using var monitor = observable.Monitor(() => utcNow);
// Act
observable.RaiseAllEvents();
// Assert
monitor.OccurredEvents[0].EventName.Should().Be(nameof(TestEventRaisingInOrder.InterfaceEvent));
monitor.OccurredEvents[0].Sequence.Should().Be(0);
monitor.OccurredEvents[1].EventName.Should().Be(nameof(TestEventRaisingInOrder.Interface2Event));
monitor.OccurredEvents[1].Sequence.Should().Be(1);
monitor.OccurredEvents[2].EventName.Should().Be(nameof(TestEventRaisingInOrder.Interface3Event));
monitor.OccurredEvents[2].Sequence.Should().Be(2);
}
[Fact]
public void When_monitoring_a_class_it_should_be_possible_to_attach_to_additional_interfaces_on_the_same_object()
{
// Arrange
var subject = new TestEventRaising();
using var outerMonitor = subject.Monitor<IEventRaisingInterface>();
using var innerMonitor = subject.Monitor<IEventRaisingInterface2>();
// Act
subject.RaiseBothEvents();
// Assert
outerMonitor.Should().Raise("InterfaceEvent");
innerMonitor.Should().Raise("Interface2Event");
}
}
public class ShouldRaisePropertyChanged
{
[Fact]
public void When_a_property_changed_event_was_raised_for_the_expected_property_it_should_not_throw()
{
// Arrange
var subject = new EventRaisingClass();
using var monitor = subject.Monitor();
subject.RaiseEventWithSenderAndPropertyName("SomeProperty");
subject.RaiseEventWithSenderAndPropertyName("SomeOtherProperty");
// Act
Action act = () => monitor.Should().RaisePropertyChangeFor(x => x.SomeProperty);
// Assert
act.Should().NotThrow();
}
[Fact]
public void When_an_expected_property_changed_event_was_raised_for_all_properties_it_should_not_throw()
{
// Arrange
var subject = new EventRaisingClass();
using var monitor = subject.Monitor();
subject.RaiseEventWithSenderAndPropertyName(null);
// Act
Action act = () => monitor.Should().RaisePropertyChangeFor(null);
// Assert
act.Should().NotThrow();
}
[Fact]
public void When_a_property_changed_event_for_a_specific_property_was_not_raised_it_should_throw()
{
// Arrange
var subject = new EventRaisingClass();
using var monitor = subject.Monitor();
// Act
Action act = () => monitor.Should().RaisePropertyChangeFor(x => x.SomeProperty, "the property was changed");
// Assert
act.Should().Throw<XunitException>().WithMessage(
"Expected object " + Formatter.ToString(subject) +
" to raise event \"PropertyChanged\" for property \"SomeProperty\" because the property was changed, but it did not*");
}
[Fact]
public void When_a_property_agnostic_property_changed_event_for_was_not_raised_it_should_throw()
{
// Arrange
var subject = new EventRaisingClass();
using var monitor = subject.Monitor();
// Act
Action act = () => monitor.Should().RaisePropertyChangeFor(null);
// Assert
act.Should().Throw<XunitException>().WithMessage(
"Expected object " + Formatter.ToString(subject) +
" to raise event \"PropertyChanged\" for property <null>, but it did not*");
}
[Fact]
public void When_the_property_changed_event_was_raised_for_the_wrong_property_it_should_throw_and_include_the_actual_properties_raised()
{
// Arrange
var bar = new EventRaisingClass();
using var monitor = bar.Monitor();
bar.RaiseEventWithSenderAndPropertyName("OtherProperty1");
bar.RaiseEventWithSenderAndPropertyName("OtherProperty2");
bar.RaiseEventWithSenderAndPropertyName("OtherProperty2");
// Act
Action act = () => monitor.Should().RaisePropertyChangeFor(b => b.SomeProperty);
// Assert
act.Should().Throw<XunitException>()
.WithMessage("Expected*property*SomeProperty*but*OtherProperty1*OtherProperty2*");
}
}
public class ShouldNotRaisePropertyChanged
{
[Fact]
public void When_a_property_changed_event_was_raised_by_monitored_class_it_should_be_possible_to_reset_the_event_monitor()
{
// Arrange
var subject = new EventRaisingClass();
using var eventMonitor = subject.Monitor();
subject.RaiseEventWithSenderAndPropertyName("SomeProperty");
// Act
eventMonitor.Clear();
// Assert
eventMonitor.Should().NotRaisePropertyChangeFor(e => e.SomeProperty);
}
[Fact]
public void When_a_property_changed_event_for_an_unexpected_property_was_raised_it_should_throw()
{
// Arrange
var subject = new EventRaisingClass();
using var monitor = subject.Monitor();
subject.RaiseEventWithSenderAndPropertyName("SomeProperty");
// Act
Action act = () => monitor.Should().NotRaisePropertyChangeFor(x => x.SomeProperty, "nothing happened");
// Assert
act.Should().Throw<XunitException>().WithMessage(
"Did not expect object " + Formatter.ToString(subject) +
" to raise the \"PropertyChanged\" event for property \"SomeProperty\" because nothing happened, but it did.");
}
[Fact]
public void When_a_property_changed_event_for_another_than_the_unexpected_property_was_raised_it_should_not_throw()
{
// Arrange
var subject = new EventRaisingClass();
using var monitor = subject.Monitor();
subject.RaiseEventWithSenderAndPropertyName("SomeOtherProperty");
// Act
Action act = () => monitor.Should().NotRaisePropertyChangeFor(x => x.SomeProperty);
// Assert
act.Should().NotThrow();
}
}
public class PreconditionChecks
{
[Fact]
public void When_monitoring_a_null_object_it_should_throw()
{
// Arrange
EventRaisingClass subject = null;
// Act
Action act = () => subject.Monitor();
// Assert
act.Should().Throw<ArgumentNullException>()
.WithMessage("Cannot monitor the events of a <null> object*");
}
[Fact]
public void When_nesting_monitoring_requests_scopes_should_be_isolated()
{
// Arrange
var eventSource = new EventRaisingClass();
using var outerScope = eventSource.Monitor();
// Act
using var innerScope = eventSource.Monitor();
// Assert
((object)innerScope).Should().NotBeSameAs(outerScope);
}
[Fact]
public void When_monitoring_an_object_with_invalid_property_expression_it_should_throw()
{
// Arrange
var eventSource = new EventRaisingClass();
using var monitor = eventSource.Monitor();
Func<EventRaisingClass, int> func = e => e.SomeOtherProperty;
// Act
Action act = () => monitor.Should().RaisePropertyChangeFor(e => func(e));
// Assert
act.Should().Throw<ArgumentException>()
.WithParameterName("expression");
}
}
public class Metadata
{
[Fact]
public void When_monitoring_an_object_it_should_monitor_all_the_events_it_exposes()
{
// Arrange
var eventSource = new ClassThatRaisesEventsItself();
using var eventMonitor = eventSource.Monitor();
// Act
EventMetadata[] metadata = eventMonitor.MonitoredEvents;
// Assert
metadata.Should().BeEquivalentTo(new[]
{
new
{
EventName = nameof(ClassThatRaisesEventsItself.InterfaceEvent),
HandlerType = typeof(EventHandler)
},
new
{
EventName = nameof(ClassThatRaisesEventsItself.PropertyChanged),
HandlerType = typeof(PropertyChangedEventHandler)
}
});
}
[Fact]
public void When_monitoring_an_object_through_an_interface_it_should_monitor_only_the_events_it_exposes()
{
// Arrange
var eventSource = new ClassThatRaisesEventsItself();
using var monitor = eventSource.Monitor<IEventRaisingInterface>();
// Act
EventMetadata[] metadata = monitor.MonitoredEvents;
// Assert
metadata.Should().BeEquivalentTo(new[]
{
new
{
EventName = nameof(IEventRaisingInterface.InterfaceEvent),
HandlerType = typeof(EventHandler)
}
});
}
#if NETFRAMEWORK // DefineDynamicAssembly is obsolete in .NET Core
[Fact]
public void When_an_object_doesnt_expose_any_events_it_should_throw()
{
// Arrange
object eventSource = CreateProxyObject();
// Act
Action act = () => eventSource.Monitor();
// Assert
act.Should().Throw<InvalidOperationException>().WithMessage("*not expose any events*");
}
[Fact]
public void When_monitoring_interface_of_a_class_and_no_recorder_exists_for_an_event_it_should_throw()
{
// Arrange
var eventSource = (IEventRaisingInterface)CreateProxyObject();
using var eventMonitor = eventSource.Monitor();
// Act
Action action = () => eventMonitor.GetRecordingFor("SomeEvent");
// Assert
action.Should().Throw<InvalidOperationException>()
.WithMessage("Not monitoring any events named \"SomeEvent\".");
}
private object CreateProxyObject()
{
Type baseType = typeof(EventRaisingClass);
Type interfaceType = typeof(IEventRaisingInterface);
AssemblyName assemblyName = new AssemblyName { Name = baseType.Assembly.FullName + ".GeneratedForTest" };
AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName,
AssemblyBuilderAccess.Run);
ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule(assemblyName.Name, false);
string typeName = baseType.Name + "_GeneratedForTest";
TypeBuilder typeBuilder = moduleBuilder.DefineType(typeName, TypeAttributes.Public, baseType, new[] { interfaceType });
MethodBuilder addHandler = EmitAddRemoveEventHandler("add");
typeBuilder.DefineMethodOverride(addHandler, interfaceType.GetMethod("add_InterfaceEvent"));
MethodBuilder removeHandler = EmitAddRemoveEventHandler("remove");
typeBuilder.DefineMethodOverride(removeHandler, interfaceType.GetMethod("remove_InterfaceEvent"));
Type generatedType = typeBuilder.CreateType();
return Activator.CreateInstance(generatedType);
MethodBuilder EmitAddRemoveEventHandler(string methodName)
{
MethodBuilder method =
typeBuilder.DefineMethod($"{interfaceType.FullName}.{methodName}_InterfaceEvent",
MethodAttributes.Private | MethodAttributes.Virtual | MethodAttributes.Final |
MethodAttributes.HideBySig |
MethodAttributes.NewSlot);
method.SetReturnType(typeof(void));
method.SetParameters(typeof(EventHandler));
ILGenerator gen = method.GetILGenerator();
gen.Emit(OpCodes.Ret);
return method;
}
}
#endif
[Fact]
public void When_event_exists_on_class_but_not_on_monitored_interface_it_should_not_allow_monitoring_it()
{
// Arrange
var eventSource = new ClassThatRaisesEventsItself();
using var eventMonitor = eventSource.Monitor<IEventRaisingInterface>();
// Act
Action action = () => eventMonitor.GetRecordingFor("PropertyChanged");
// Assert
action.Should().Throw<InvalidOperationException>()
.WithMessage("Not monitoring any events named \"PropertyChanged\".");
}
[Fact]
public void When_an_object_raises_two_events_it_should_provide_the_data_about_those_occurrences()
{
// Arrange
DateTime utcNow = 17.September(2017).At(21, 00).AsUtc();
var eventSource = new EventRaisingClass();
using var monitor = eventSource.Monitor(() => utcNow);
// Act
eventSource.RaiseEventWithSenderAndPropertyName("theProperty");
utcNow += 1.Hours();
eventSource.RaiseNonConventionalEvent("first", 123, "third");
// Assert
monitor.OccurredEvents.Should().BeEquivalentTo(new[]
{
new
{
EventName = "PropertyChanged",
TimestampUtc = utcNow - 1.Hours(),
Parameters = new object[] { eventSource, new PropertyChangedEventArgs("theProperty") }
},
new
{
EventName = "NonConventionalEvent",
TimestampUtc = utcNow,
Parameters = new object[] { "first", 123, "third" }
}
}, o => o.WithStrictOrdering());
}
[Fact]
public void When_monitoring_interface_with_inherited_event_it_should_not_throw()
{
// Arrange
var eventSource = (IInheritsEventRaisingInterface)new ClassThatRaisesEventsItself();
// Act
Action action = () => eventSource.Monitor();
// Assert
action.Should().NotThrow<InvalidOperationException>();
}
}
public class WithArgs
{
[Fact]
public void One_matching_argument_type_before_mismatching_types_passes()
{
// Arrange
A a = new A();
using var aMonitor = a.Monitor();
a.OnEvent(new B());
a.OnEvent(new C());
// Act / Assert
IEventRecording filteredEvents = aMonitor.GetRecordingFor(nameof(A.Event)).WithArgs<B>();
filteredEvents.Should().HaveCount(1);
}
[Fact]
public void One_matching_argument_type_after_mismatching_types_passes()
{
// Arrange
A a = new A();
using var aMonitor = a.Monitor();
a.OnEvent(new C());
a.OnEvent(new B());
// Act / Assert
IEventRecording filteredEvents = aMonitor.GetRecordingFor(nameof(A.Event)).WithArgs<B>();
filteredEvents.Should().HaveCount(1);
}
[Fact]
public void Throws_when_none_of_the_arguments_are_of_the_expected_type()
{
// Arrange
A a = new A();
using var aMonitor = a.Monitor();
a.OnEvent(new C());
a.OnEvent(new C());
// Act
Action act = () => aMonitor.GetRecordingFor(nameof(A.Event)).WithArgs<B>();
// Assert
act.Should().Throw<XunitException>()
.WithMessage("Expected*event*argument*");
}
[Fact]
public void One_matching_argument_type_anywhere_between_mismatching_types_passes()
{
// Arrange
A a = new A();
using var aMonitor = a.Monitor();
a.OnEvent(new C());
a.OnEvent(new B());
a.OnEvent(new C());
// Act / Assert
IEventRecording filteredEvents = aMonitor.GetRecordingFor(nameof(A.Event)).WithArgs<B>();
filteredEvents.Should().HaveCount(1);
}
[Fact]
public void One_matching_argument_type_anywhere_between_mismatching_types_with_parameters_passes()
{
// Arrange
A a = new A();
using var aMonitor = a.Monitor();
a.OnEvent(new C());
a.OnEvent(new B());
a.OnEvent(new C());
// Act / Assert
IEventRecording filteredEvents = aMonitor.GetRecordingFor(nameof(A.Event)).WithArgs<B>(b => true);
filteredEvents.Should().HaveCount(1);
}
[Fact]
public void Mismatching_argument_types_with_one_parameter_matching_a_different_type_fails()
{
// Arrange
A a = new A();
using var aMonitor = a.Monitor();
a.OnEvent(new C());
a.OnEvent(new C());
// Act
Action act = () => aMonitor.GetRecordingFor(nameof(A.Event)).WithArgs<B>(b => true);
// Assert
act.Should().Throw<XunitException>()
.WithMessage("Expected*event*argument*type*B*none*");
}
[Fact]
public void Mismatching_argument_types_with_two_or_more_parameters_matching_a_different_type_fails()
{
// Arrange
A a = new A();
using var aMonitor = a.Monitor();
a.OnEvent(new C());
a.OnEvent(new C());
// Act
Action act = () => aMonitor.GetRecordingFor(nameof(A.Event)).WithArgs<B>(b => true, b => false);
// Assert
act.Should().Throw<ArgumentException>()
.WithMessage("Expected*event*parameters*type*B*found*");
}
[Fact]
public void One_matching_argument_type_with_two_or_more_parameters_matching_a_mismatching_type_fails()
{
// Arrange
A a = new A();
using var aMonitor = a.Monitor();
a.OnEvent(new C());
a.OnEvent(new B());
// Act
Action act = () => aMonitor.GetRecordingFor(nameof(A.Event)).WithArgs<B>(b => true, b => false);
// Assert
act.Should().Throw<ArgumentException>()
.WithMessage("Expected*event*parameters*type*B*found*");
}
}
public class A
{
public event EventHandler<object> Event;
public void OnEvent(object o)
{
Event.Invoke(nameof(A), o);
}
}
public class B { }
public class C { }
public class ClassThatRaisesEventsItself : IInheritsEventRaisingInterface
{
public event PropertyChangedEventHandler PropertyChanged;
public event EventHandler InterfaceEvent;
protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
{
PropertyChanged?.Invoke(this, e);
}
protected virtual void OnInterfaceEvent()
{
InterfaceEvent?.Invoke(this, EventArgs.Empty);
}
}
public class TestEventRaising : IEventRaisingInterface, IEventRaisingInterface2
{
public event EventHandler InterfaceEvent;
public event EventHandler Interface2Event;
public void RaiseBothEvents()
{
InterfaceEvent?.Invoke(this, EventArgs.Empty);
Interface2Event?.Invoke(this, EventArgs.Empty);
}
}
private class TestEventRaisingInOrder : IEventRaisingInterface, IEventRaisingInterface2, IEventRaisingInterface3
{
public event EventHandler Interface3Event;
public event EventHandler Interface2Event;
public event EventHandler InterfaceEvent;
public void RaiseAllEvents()