How to check callbacks using NUnit

Is there any special support when you come to check callbacks with NUnit? Or some kind of “best practice” that is better than my solution below?

I just started writing some tests and methods, so I still have full control - however, I think it can be unpleasant if there are more effective ways to test callbacks, especially if the complexity increases. So this is a simple example of how I'm testing right now:

The test method uses a delegate that calls the callback function, for example, as soon as a new xml element is detected in the stream. For testing purposes, I pass the method to the NewElementCallbackdelegate and save the contents of the arguments in some properties of the test classes when the function is called. I use these properties for approval. (Of course, they are in reset in the test setup)

[Test]
public void NewElement()
{
    String xmlString = @"<elem></elem>";

    this.xml.InputStream = new StringReader(xmlString);
    this.xml.NewElement += this.NewElementCallback;

    this.xml.Start();

    Assert.AreEqual("elem", this.elementName);
    Assert.AreEqual(0, this.elementDepth);
}

private void NewElementCallback(string elementName, int elementDepth)
{
    this.elementName = elementName;
    this.elementDepth = elementDepth;
}
+3
source share
3 answers

You can avoid the need to use private fields if you use a lambda expression, as I usually do.

[Test]
public void NewElement()
{
    String xmlString = @"<elem></elem>";
    string elementName;
    int elementDepth;

    this.xml.InputStream = new StringReader(xmlString);
    this.xml.NewElement += (name,depth) => { elementName = name; elementDepth = depth };

    this.xml.Start();

    Assert.AreEqual("elem", elementName);
    Assert.AreEqual(0, elementDepth);
}

this makes your tests more cohesive, and fields on any test class always require disaster!

+4

NUnit , . , . , . , , .

0

From your example, I can’t say exactly what you are trying to do, however, NUnit does not provide any specific ways to test such things, however this link should give you some ideas on how to start modular asynchronous code: Testing devices Asynchronous code

0
source

Source: https://habr.com/ru/post/1760802/


All Articles