How to check function returns IEnumerable <Integer>

I am trying to test a function

public static IEnumerable<Integer> Divisors(Integer n)
{
    int max = (int)System.Math.Sqrt(n);

    if (n != 0)
        yield return 1;

    for (int i = 2; i <= max; i++)
        if (n % i == 0)
            yield return i;
}

and I need to write a test function like

[Test]
public void DivisorsTest()
{   
    Integer n = 0; 
    IEnumerable<Integer> expected = 0 ; //error
    IEnumerable<Integer> actual;
    actual = Science.Mathematics.NumberTheoryFunctions.Divisors(n);
    Assert.AreEqual(expected, actual);
}

How can I change this line to test the output that I need to check return values ​​that are not only null

+3
source share
5 answers

OK, thanks to everyone for your answers, and here is what I did with your answers

test functions will be: 1- when you expect the function to return no value

[Test]
   public void DivisorsTest_01()
   {   
       Integer n = 0; 
       IEnumerable<Integer> actual;
       actual = Science.Mathematics.NumberTheoryFunctions.Divisors(n);
       Assert.IsFalse(actual.Any()); // There should not be any elements returned so empty
   }

2- all you need is to convert o / p to an array and use it:

[Test]
   public void DivisorsTest_03()
   {
       Integer n = 9;
       Integer[] expected = new Integer[3] { 1,3,9 };
       IEnumerable<Integer> actual;
       actual = Science.Mathematics.NumberTheoryFunctions.Divisors(n);
       var actual1 = actual.ToArray();

       Assert.AreEqual(expected[0], actual1[0]);
       Assert.AreEqual(expected[1], actual1[1]);
       Assert.AreEqual(expected[2], actual1[2]);

   }

3- sometimes you expect the output to be an exception, so be sure to write:

[Test]
[ExpectedException]

before function.

thanks again everyone

0

. , , (.. ), :

Assert.IsFalse(actual.Any()); // There should not be any elements returned

:

var results = actual.ToArray();
Assert.AreEqual(5, results.Count);
Assert.AreEqual(1, results[0]);
Assert.AreEqual(2, results[1]);
// etc.
+2

- (, Linq):

[Test]
public void DivisorsTest()
{   
    int n = 0; 
    int expected = 0; //error
    IEnumerable<Integer> actual;
    actual = Science.Mathematics.NumberTheoryFunctions.Divisors(n);
    Assert.IsTrue(actual.All(x => x != expected));
}
0

(.. ),

IEnumerable<int> expected = System.Linq.Enumerable.Empty<int>();

MSDN

0

- :

var expected = new int[] { /* expected values */ };
var actual = Science.Mathematics.NumberTheoryFunctions.Divisors(n);
Assert.IsTrue(expected.SequenceEquals(actual));

, , :

Expected: True
But was: False

CollectionAssert.AreEquivalent, , ... Linq, :

Expected: equivalent to < 0, 1, 3, 4, 6, 7, 9, 10 >
But was:  <System.Linq.Enumerable+<WhereIterator>d__0`1[System.Int32]>

(at least with NUnit 2.4.8, maybe I need to upgrade to a newer version ...)

0
source

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


All Articles