How to test if no event was invoked

How to test if no event was invoked



I am new to UnitTests and therefore to Xunit. I have wrote some tests, but I am stuck with the testing of events.



Is it possible to test that no event was invoked with xunit?



I used this example for preparing my tests.



The first test works fine. For the second test, I expected something like 'Assert.RaisesNoEvent'; However, that method is not available.



Is there another way to test that no event was invoked?



Class where Event is Raised when Property2 is Set


Class


Property2


Set


public class Class

private int _property2;

public event EventHandler RelevantPropertyChanged;
public void OnRelevantPropertyChanged(EventArgs args)
RelevantPropertyChanged?.Invoke(this, args);


public int Property1 get; set;
public int Property2
get return _property2;
set
OnRelevantPropertyChanged(new EventArgs());
_property2 = value;





TestClass defines unit tests for Class


TestClass


Class


public class TestClass


[Fact]
public void ChangeProperty2_RaisesEvent()

var cl = new Class();
var args = new EventArgs();

var evt = Assert.RaisesAny<EventArgs>(
h => cl.RelevantPropertyChanged += h,
h => cl.RelevantPropertyChanged -= h,
() => cl.Property2 = 5);

Assert.NotNull(evt);
Assert.Equal(cl, evt.Sender);
Assert.Equal(args, evt.Arguments);


[Fact]
public void ChangeProperty1_RaisesNoEvent()

var cl = new Class();
Action code = () => cl.Property1 = 5;

Assert.RaisesNoEvent(code); //this is what I want to do






Imagine you want to test a function which updates a specific row in a database table, you could test if the other rows haven't changed, for instance to verify the WHERE clause has not been omitted and is correct. But would you also want to verify if all other records in all other tables are unaltered?
– Bouke
Aug 25 at 17:52




1 Answer
1



You can check that the event was not raised by checking that the EventHandler was not invoked:


[Fact]
public void ChangeProperty1_RaisesNoEvent()

var instance = new Class();
bool isInvoked = false;
instance.RelevantPropertyChanged += (s, e) => isInvoked = true;

Assert.False(isInvoked);
instance.Property1 = 5;
Assert.False(isInvoked);



This technique works with any unit testing framework.






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)