Serlok
Serlok

Reputation: 462

How to pass string and dictionary in NUnit test cases?

I want to make test for my method and I can pass 2 string variables, but I don't know how to pass the Dictionary<,>.

It looks like this:

[Test]
[TestCase("agr1", "askdwskdls", Dictionary<TypeMeasurement,double>)]
public void SendDataToAgregator_GoodVariables_ReturnsOn(string agrID,string devID, Dictionary<TypeMeasurement, double> measurement)
{

}

TypeMeasurement is enum and I know that this is not how you pass dictionary, but I don't know how, so I place it there so that you know what I want to do.

Upvotes: 5

Views: 6701

Answers (1)

CodeNotFound
CodeNotFound

Reputation: 23200

Instead of TestCaseAttribute, if you have complex data to use as a test case, you should look at TestCaseSourceAttribute

TestCaseSourceAttribute is used on a parameterized test method to identify the property, method or field that will provide the required arguments

You can use one of the following contructors:

TestCaseSourceAttribute(Type sourceType, string sourceName);
TestCaseSourceAttribute(string sourceName);

This is explantion from the documentation:

If sourceType is specified, it represents the class that provides the test cases. It must have a default constructor.

If sourceType is not specified, the class containing the test method is used. NUnit will construct it using either the default constructor or - if arguments are provided - the appropriate constructor for those arguments.

So you can use it like below:

[Test]
[TestCaseSource(nameof(MySourceMethod))]
public void SendDataToAgregator_GoodVariables_ReturnsOn(string agrID,string devID, Dictionary<TypeMeasurement, double> measurement)
{

}

static IEnumerable<object[]> MySourceMethod()
{
    var measurement = new Dictionary<TypeMeasurement, double>();
    // Do what you want with your dictionary

    // The order of element in the object my be the same expected by your test method
    return new[] { new object[] { "agr1", "askdwskdls", measurement }, };
};

Upvotes: 10

Related Questions