Assert.Throws method doesn't catch the expected exceptionCreate Generic method constraining T to an EnumCatch multiple exceptions at once?Why is it important to override GetHashCode when Equals method is overridden?Expect exceptions in nUnit without the ExpectedException attributeWhy catch and rethrow an exception in C#?How do I use Assert.Throws to assert the type of the exception?How to mark a method as obsolete or deprecated?Try-catch speeding up my code?Use NUnit Assert.Throws method or ExpectedException attribute?Issue with Assert.Throws Exception in NUnit testing

Does George B Sperry logo on fold case for photos indicate photographer or case manufacturer?

Why is this python script running in background consuming 100 % CPU?

Is there a word for pant sleeves?

Circuit construction for execution of conditional statements using least significant bit

How do you cope with rejection?

Why was Harry at the Weasley's at the beginning of Goblet of Fire but at the Dursleys' after?

Do 'destroy' effects count as damage?

Do most Taxis give Receipts in London?

Story about encounter with hostile aliens

How to tease a romance without a cat and mouse chase?

US F1 Visa grace period attending a conference

What should I wear to go and sign an employment contract?

If the Charles SSL Proxy shows me sensitive data, is that data insecure/exposed?

Is being an extrovert a necessary condition to be a manager?

Way of refund if scammed?

What does it mean to "take the Cross"

Why use nominative in Coniugatio periphrastica passiva?

List of lists elementwise greater/smaller than

On a piano, are the effects of holding notes and the sustain pedal the same for a single chord?

How to safely discharge oneself

Best practice for printing and evaluating formulas with the minimal coding

How to become an Editorial board member?

If you attack a Tarrasque while swallowed, what AC do you need to beat to hit it?

Presenting 2 results for one variable using a left brace



Assert.Throws method doesn't catch the expected exception


Create Generic method constraining T to an EnumCatch multiple exceptions at once?Why is it important to override GetHashCode when Equals method is overridden?Expect exceptions in nUnit without the ExpectedException attributeWhy catch and rethrow an exception in C#?How do I use Assert.Throws to assert the type of the exception?How to mark a method as obsolete or deprecated?Try-catch speeding up my code?Use NUnit Assert.Throws method or ExpectedException attribute?Issue with Assert.Throws Exception in NUnit testing






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








7















I'm trying to test a really simple function. It returns numbers which contain some specified digit. If the first argument is null, it'll throw ArgumentNullException.



Unfortunately, Assert.Throws says, that the expected exception isn't thrown and the test fails. When I'm trying to debug the test, it doesn't step into my method. The same thing with ArgumentException.



Only the two last tests fail, others are successful.



My function to be tested:



 /// <summary>
/// Filter given numbers and return only numbers containing the specified digit.
/// </summary>
/// <param name="numbers">The numbers to be filtered.</param>
/// <param name="digit">The digit which should be found.</param>
/// <returns>Numbers that contains the digit.</returns>
/// <exception cref="ArgumentException"> Thrown if the digit value isn't between 0 and 9.</exception>
/// <exception cref="ArgumentNullException"> Thrown if numbers are null.</exception>
public static IEnumerable<int> FilterDigits(IEnumerable<int> numbers, byte digit)

if (numbers == null)

throw new ArgumentNullException();


foreach (int number in numbers)

if (number.ContainsDigit(digit))

yield return number;




/// <summary>
/// Check whether the number contains the given digit.
/// </summary>
/// <param name="number">The number which can contain the digit.</param>
/// <param name="digit">The digit to be found.</param>
/// <returns>True if the number contains the digit, else false.</returns>
/// <exception cref="ArgumentException"> Thrown if the digit value isn't between 0 and 9.</exception>
/// <example> ContainsDigit(10, 1) -> true </example>
/// <example> ContainsDigit(10, 2) -> false </example>
private static bool ContainsDigit(this int number, byte digit)

if (!char.TryParse(digit.ToString(), out char digitChar))

throw new ArgumentException("The digit should be from 0 to 9.");


string numberString = number.ToString();

foreach (char ch in numberString)

if (ch == digitChar)

return true;



return false;



My test class:



[TestFixture]
public class DigitsFilterTests

[TestCase(new int[] 1, 4, 23, 346, 7, 23, 87, 71, 77 , 7, ExpectedResult = new int[] 7, 87, 71, 77 )]
[TestCase(new int[] 345, 4, 0, 90, 709 , 0, ExpectedResult = new int[] 0, 90, 709)]
public IEnumerable<int> FilterDigits_NumbersContainDigit(int[] numbers, byte digit)
=> DigitsFilter.FilterDigits(numbers, digit);

[TestCase(new int[] 1, 4, 222, 9302 , 7, ExpectedResult = new int[] )]
[TestCase(new int[] 345, 4, 354, 25, 5 , 0, ExpectedResult = new int[] )]
public IEnumerable<int> FilterDigits_NumbersNotContainDigit(int[] numbers, byte digit)
=> DigitsFilter.FilterDigits(numbers, digit);

[TestCase(new int[] , 0, ExpectedResult = new int[] )]
public IEnumerable<int> FilterDigits_EmptyList(int[] numbers, byte digit)
=> DigitsFilter.FilterDigits(numbers, digit);

[Test]
public void FilterDigits_NullNumbers_ArgumentNullException()
=> Assert.Throws<ArgumentNullException>(() => DigitsFilter.FilterDigits(null, 5));

[Test]
public void FilterDigits_InvalidDigit_ArgumentException()
=> Assert.Throws<ArgumentException>(() => DigitsFilter.FilterDigits(new int[] , 10));










share|improve this question
























  • In Visual studio, in the source code of your test class, move the text cursor onto FilterDigits of the code line containing DigitsFilter.FilterDigits(...). Then hit F12. It will jump to the actual implementation of this method. Is the implementation you see there actually the implementation you believe it is? (I am assuming both your main project and your test project are in the same VS solution). If it is, try the "restart VS, clean the solution, rebuild the solution" spiel...

    – elgonzo
    Mar 23 at 19:44












  • Yeah, it's the right method. After rebuilding the solution and restarting VS nothing changed.

    – Karalina Dubitskaya
    Mar 23 at 19:52

















7















I'm trying to test a really simple function. It returns numbers which contain some specified digit. If the first argument is null, it'll throw ArgumentNullException.



Unfortunately, Assert.Throws says, that the expected exception isn't thrown and the test fails. When I'm trying to debug the test, it doesn't step into my method. The same thing with ArgumentException.



Only the two last tests fail, others are successful.



My function to be tested:



 /// <summary>
/// Filter given numbers and return only numbers containing the specified digit.
/// </summary>
/// <param name="numbers">The numbers to be filtered.</param>
/// <param name="digit">The digit which should be found.</param>
/// <returns>Numbers that contains the digit.</returns>
/// <exception cref="ArgumentException"> Thrown if the digit value isn't between 0 and 9.</exception>
/// <exception cref="ArgumentNullException"> Thrown if numbers are null.</exception>
public static IEnumerable<int> FilterDigits(IEnumerable<int> numbers, byte digit)

if (numbers == null)

throw new ArgumentNullException();


foreach (int number in numbers)

if (number.ContainsDigit(digit))

yield return number;




/// <summary>
/// Check whether the number contains the given digit.
/// </summary>
/// <param name="number">The number which can contain the digit.</param>
/// <param name="digit">The digit to be found.</param>
/// <returns>True if the number contains the digit, else false.</returns>
/// <exception cref="ArgumentException"> Thrown if the digit value isn't between 0 and 9.</exception>
/// <example> ContainsDigit(10, 1) -> true </example>
/// <example> ContainsDigit(10, 2) -> false </example>
private static bool ContainsDigit(this int number, byte digit)

if (!char.TryParse(digit.ToString(), out char digitChar))

throw new ArgumentException("The digit should be from 0 to 9.");


string numberString = number.ToString();

foreach (char ch in numberString)

if (ch == digitChar)

return true;



return false;



My test class:



[TestFixture]
public class DigitsFilterTests

[TestCase(new int[] 1, 4, 23, 346, 7, 23, 87, 71, 77 , 7, ExpectedResult = new int[] 7, 87, 71, 77 )]
[TestCase(new int[] 345, 4, 0, 90, 709 , 0, ExpectedResult = new int[] 0, 90, 709)]
public IEnumerable<int> FilterDigits_NumbersContainDigit(int[] numbers, byte digit)
=> DigitsFilter.FilterDigits(numbers, digit);

[TestCase(new int[] 1, 4, 222, 9302 , 7, ExpectedResult = new int[] )]
[TestCase(new int[] 345, 4, 354, 25, 5 , 0, ExpectedResult = new int[] )]
public IEnumerable<int> FilterDigits_NumbersNotContainDigit(int[] numbers, byte digit)
=> DigitsFilter.FilterDigits(numbers, digit);

[TestCase(new int[] , 0, ExpectedResult = new int[] )]
public IEnumerable<int> FilterDigits_EmptyList(int[] numbers, byte digit)
=> DigitsFilter.FilterDigits(numbers, digit);

[Test]
public void FilterDigits_NullNumbers_ArgumentNullException()
=> Assert.Throws<ArgumentNullException>(() => DigitsFilter.FilterDigits(null, 5));

[Test]
public void FilterDigits_InvalidDigit_ArgumentException()
=> Assert.Throws<ArgumentException>(() => DigitsFilter.FilterDigits(new int[] , 10));










share|improve this question
























  • In Visual studio, in the source code of your test class, move the text cursor onto FilterDigits of the code line containing DigitsFilter.FilterDigits(...). Then hit F12. It will jump to the actual implementation of this method. Is the implementation you see there actually the implementation you believe it is? (I am assuming both your main project and your test project are in the same VS solution). If it is, try the "restart VS, clean the solution, rebuild the solution" spiel...

    – elgonzo
    Mar 23 at 19:44












  • Yeah, it's the right method. After rebuilding the solution and restarting VS nothing changed.

    – Karalina Dubitskaya
    Mar 23 at 19:52













7












7








7








I'm trying to test a really simple function. It returns numbers which contain some specified digit. If the first argument is null, it'll throw ArgumentNullException.



Unfortunately, Assert.Throws says, that the expected exception isn't thrown and the test fails. When I'm trying to debug the test, it doesn't step into my method. The same thing with ArgumentException.



Only the two last tests fail, others are successful.



My function to be tested:



 /// <summary>
/// Filter given numbers and return only numbers containing the specified digit.
/// </summary>
/// <param name="numbers">The numbers to be filtered.</param>
/// <param name="digit">The digit which should be found.</param>
/// <returns>Numbers that contains the digit.</returns>
/// <exception cref="ArgumentException"> Thrown if the digit value isn't between 0 and 9.</exception>
/// <exception cref="ArgumentNullException"> Thrown if numbers are null.</exception>
public static IEnumerable<int> FilterDigits(IEnumerable<int> numbers, byte digit)

if (numbers == null)

throw new ArgumentNullException();


foreach (int number in numbers)

if (number.ContainsDigit(digit))

yield return number;




/// <summary>
/// Check whether the number contains the given digit.
/// </summary>
/// <param name="number">The number which can contain the digit.</param>
/// <param name="digit">The digit to be found.</param>
/// <returns>True if the number contains the digit, else false.</returns>
/// <exception cref="ArgumentException"> Thrown if the digit value isn't between 0 and 9.</exception>
/// <example> ContainsDigit(10, 1) -> true </example>
/// <example> ContainsDigit(10, 2) -> false </example>
private static bool ContainsDigit(this int number, byte digit)

if (!char.TryParse(digit.ToString(), out char digitChar))

throw new ArgumentException("The digit should be from 0 to 9.");


string numberString = number.ToString();

foreach (char ch in numberString)

if (ch == digitChar)

return true;



return false;



My test class:



[TestFixture]
public class DigitsFilterTests

[TestCase(new int[] 1, 4, 23, 346, 7, 23, 87, 71, 77 , 7, ExpectedResult = new int[] 7, 87, 71, 77 )]
[TestCase(new int[] 345, 4, 0, 90, 709 , 0, ExpectedResult = new int[] 0, 90, 709)]
public IEnumerable<int> FilterDigits_NumbersContainDigit(int[] numbers, byte digit)
=> DigitsFilter.FilterDigits(numbers, digit);

[TestCase(new int[] 1, 4, 222, 9302 , 7, ExpectedResult = new int[] )]
[TestCase(new int[] 345, 4, 354, 25, 5 , 0, ExpectedResult = new int[] )]
public IEnumerable<int> FilterDigits_NumbersNotContainDigit(int[] numbers, byte digit)
=> DigitsFilter.FilterDigits(numbers, digit);

[TestCase(new int[] , 0, ExpectedResult = new int[] )]
public IEnumerable<int> FilterDigits_EmptyList(int[] numbers, byte digit)
=> DigitsFilter.FilterDigits(numbers, digit);

[Test]
public void FilterDigits_NullNumbers_ArgumentNullException()
=> Assert.Throws<ArgumentNullException>(() => DigitsFilter.FilterDigits(null, 5));

[Test]
public void FilterDigits_InvalidDigit_ArgumentException()
=> Assert.Throws<ArgumentException>(() => DigitsFilter.FilterDigits(new int[] , 10));










share|improve this question
















I'm trying to test a really simple function. It returns numbers which contain some specified digit. If the first argument is null, it'll throw ArgumentNullException.



Unfortunately, Assert.Throws says, that the expected exception isn't thrown and the test fails. When I'm trying to debug the test, it doesn't step into my method. The same thing with ArgumentException.



Only the two last tests fail, others are successful.



My function to be tested:



 /// <summary>
/// Filter given numbers and return only numbers containing the specified digit.
/// </summary>
/// <param name="numbers">The numbers to be filtered.</param>
/// <param name="digit">The digit which should be found.</param>
/// <returns>Numbers that contains the digit.</returns>
/// <exception cref="ArgumentException"> Thrown if the digit value isn't between 0 and 9.</exception>
/// <exception cref="ArgumentNullException"> Thrown if numbers are null.</exception>
public static IEnumerable<int> FilterDigits(IEnumerable<int> numbers, byte digit)

if (numbers == null)

throw new ArgumentNullException();


foreach (int number in numbers)

if (number.ContainsDigit(digit))

yield return number;




/// <summary>
/// Check whether the number contains the given digit.
/// </summary>
/// <param name="number">The number which can contain the digit.</param>
/// <param name="digit">The digit to be found.</param>
/// <returns>True if the number contains the digit, else false.</returns>
/// <exception cref="ArgumentException"> Thrown if the digit value isn't between 0 and 9.</exception>
/// <example> ContainsDigit(10, 1) -> true </example>
/// <example> ContainsDigit(10, 2) -> false </example>
private static bool ContainsDigit(this int number, byte digit)

if (!char.TryParse(digit.ToString(), out char digitChar))

throw new ArgumentException("The digit should be from 0 to 9.");


string numberString = number.ToString();

foreach (char ch in numberString)

if (ch == digitChar)

return true;



return false;



My test class:



[TestFixture]
public class DigitsFilterTests

[TestCase(new int[] 1, 4, 23, 346, 7, 23, 87, 71, 77 , 7, ExpectedResult = new int[] 7, 87, 71, 77 )]
[TestCase(new int[] 345, 4, 0, 90, 709 , 0, ExpectedResult = new int[] 0, 90, 709)]
public IEnumerable<int> FilterDigits_NumbersContainDigit(int[] numbers, byte digit)
=> DigitsFilter.FilterDigits(numbers, digit);

[TestCase(new int[] 1, 4, 222, 9302 , 7, ExpectedResult = new int[] )]
[TestCase(new int[] 345, 4, 354, 25, 5 , 0, ExpectedResult = new int[] )]
public IEnumerable<int> FilterDigits_NumbersNotContainDigit(int[] numbers, byte digit)
=> DigitsFilter.FilterDigits(numbers, digit);

[TestCase(new int[] , 0, ExpectedResult = new int[] )]
public IEnumerable<int> FilterDigits_EmptyList(int[] numbers, byte digit)
=> DigitsFilter.FilterDigits(numbers, digit);

[Test]
public void FilterDigits_NullNumbers_ArgumentNullException()
=> Assert.Throws<ArgumentNullException>(() => DigitsFilter.FilterDigits(null, 5));

[Test]
public void FilterDigits_InvalidDigit_ArgumentException()
=> Assert.Throws<ArgumentException>(() => DigitsFilter.FilterDigits(new int[] , 10));







c# nunit






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 23 at 21:57









grooveplex

1,35221625




1,35221625










asked Mar 23 at 19:38









Karalina DubitskayaKaralina Dubitskaya

384




384












  • In Visual studio, in the source code of your test class, move the text cursor onto FilterDigits of the code line containing DigitsFilter.FilterDigits(...). Then hit F12. It will jump to the actual implementation of this method. Is the implementation you see there actually the implementation you believe it is? (I am assuming both your main project and your test project are in the same VS solution). If it is, try the "restart VS, clean the solution, rebuild the solution" spiel...

    – elgonzo
    Mar 23 at 19:44












  • Yeah, it's the right method. After rebuilding the solution and restarting VS nothing changed.

    – Karalina Dubitskaya
    Mar 23 at 19:52

















  • In Visual studio, in the source code of your test class, move the text cursor onto FilterDigits of the code line containing DigitsFilter.FilterDigits(...). Then hit F12. It will jump to the actual implementation of this method. Is the implementation you see there actually the implementation you believe it is? (I am assuming both your main project and your test project are in the same VS solution). If it is, try the "restart VS, clean the solution, rebuild the solution" spiel...

    – elgonzo
    Mar 23 at 19:44












  • Yeah, it's the right method. After rebuilding the solution and restarting VS nothing changed.

    – Karalina Dubitskaya
    Mar 23 at 19:52
















In Visual studio, in the source code of your test class, move the text cursor onto FilterDigits of the code line containing DigitsFilter.FilterDigits(...). Then hit F12. It will jump to the actual implementation of this method. Is the implementation you see there actually the implementation you believe it is? (I am assuming both your main project and your test project are in the same VS solution). If it is, try the "restart VS, clean the solution, rebuild the solution" spiel...

– elgonzo
Mar 23 at 19:44






In Visual studio, in the source code of your test class, move the text cursor onto FilterDigits of the code line containing DigitsFilter.FilterDigits(...). Then hit F12. It will jump to the actual implementation of this method. Is the implementation you see there actually the implementation you believe it is? (I am assuming both your main project and your test project are in the same VS solution). If it is, try the "restart VS, clean the solution, rebuild the solution" spiel...

– elgonzo
Mar 23 at 19:44














Yeah, it's the right method. After rebuilding the solution and restarting VS nothing changed.

– Karalina Dubitskaya
Mar 23 at 19:52





Yeah, it's the right method. After rebuilding the solution and restarting VS nothing changed.

– Karalina Dubitskaya
Mar 23 at 19:52












1 Answer
1






active

oldest

votes


















6














Your method is an enumerable built using yield return. What's tricky about it is that nothing will actually happen unless you enumerate it.



So you must make sure that your test enumerates the contents:



 [Test]
public void FilterDigits_NullNumbers_ArgumentNullException()
=> Assert.Throws<ArgumentNullException>(() => DigitsFilter.FilterDigits(null, 5).ToList());


Also, your second test will fail either way because you won't reach ContainsDigit if numbers is empty.



If you want to fix the behavior inside of the method, you need to cut it into two:



public static IEnumerable<int> FilterDigits(IEnumerable<int> numbers, byte digit)

if (numbers == null)

throw new ArgumentNullException();


return FilterDigitsImpl(numbers, digit);


private static IEnumerable<int> FilterDigitsImpl(IEnumerable<int> numbers, byte digit)

foreach (int number in numbers)

if (number.ContainsDigit(digit))

yield return number;





If your version of C# is recent enough, you can merge both methods using local functions:



public static IEnumerable<int> FilterDigits(IEnumerable<int> numbers, byte digit)

if (numbers == null)

throw new ArgumentNullException();


IEnumerable<int> FilterDigitsImpl()

foreach (int number in numbers)

if (number.ContainsDigit(digit))

yield return number;




return FilterDigitsImpl();






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55317634%2fassert-throws-method-doesnt-catch-the-expected-exception%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    6














    Your method is an enumerable built using yield return. What's tricky about it is that nothing will actually happen unless you enumerate it.



    So you must make sure that your test enumerates the contents:



     [Test]
    public void FilterDigits_NullNumbers_ArgumentNullException()
    => Assert.Throws<ArgumentNullException>(() => DigitsFilter.FilterDigits(null, 5).ToList());


    Also, your second test will fail either way because you won't reach ContainsDigit if numbers is empty.



    If you want to fix the behavior inside of the method, you need to cut it into two:



    public static IEnumerable<int> FilterDigits(IEnumerable<int> numbers, byte digit)

    if (numbers == null)

    throw new ArgumentNullException();


    return FilterDigitsImpl(numbers, digit);


    private static IEnumerable<int> FilterDigitsImpl(IEnumerable<int> numbers, byte digit)

    foreach (int number in numbers)

    if (number.ContainsDigit(digit))

    yield return number;





    If your version of C# is recent enough, you can merge both methods using local functions:



    public static IEnumerable<int> FilterDigits(IEnumerable<int> numbers, byte digit)

    if (numbers == null)

    throw new ArgumentNullException();


    IEnumerable<int> FilterDigitsImpl()

    foreach (int number in numbers)

    if (number.ContainsDigit(digit))

    yield return number;




    return FilterDigitsImpl();






    share|improve this answer



























      6














      Your method is an enumerable built using yield return. What's tricky about it is that nothing will actually happen unless you enumerate it.



      So you must make sure that your test enumerates the contents:



       [Test]
      public void FilterDigits_NullNumbers_ArgumentNullException()
      => Assert.Throws<ArgumentNullException>(() => DigitsFilter.FilterDigits(null, 5).ToList());


      Also, your second test will fail either way because you won't reach ContainsDigit if numbers is empty.



      If you want to fix the behavior inside of the method, you need to cut it into two:



      public static IEnumerable<int> FilterDigits(IEnumerable<int> numbers, byte digit)

      if (numbers == null)

      throw new ArgumentNullException();


      return FilterDigitsImpl(numbers, digit);


      private static IEnumerable<int> FilterDigitsImpl(IEnumerable<int> numbers, byte digit)

      foreach (int number in numbers)

      if (number.ContainsDigit(digit))

      yield return number;





      If your version of C# is recent enough, you can merge both methods using local functions:



      public static IEnumerable<int> FilterDigits(IEnumerable<int> numbers, byte digit)

      if (numbers == null)

      throw new ArgumentNullException();


      IEnumerable<int> FilterDigitsImpl()

      foreach (int number in numbers)

      if (number.ContainsDigit(digit))

      yield return number;




      return FilterDigitsImpl();






      share|improve this answer

























        6












        6








        6







        Your method is an enumerable built using yield return. What's tricky about it is that nothing will actually happen unless you enumerate it.



        So you must make sure that your test enumerates the contents:



         [Test]
        public void FilterDigits_NullNumbers_ArgumentNullException()
        => Assert.Throws<ArgumentNullException>(() => DigitsFilter.FilterDigits(null, 5).ToList());


        Also, your second test will fail either way because you won't reach ContainsDigit if numbers is empty.



        If you want to fix the behavior inside of the method, you need to cut it into two:



        public static IEnumerable<int> FilterDigits(IEnumerable<int> numbers, byte digit)

        if (numbers == null)

        throw new ArgumentNullException();


        return FilterDigitsImpl(numbers, digit);


        private static IEnumerable<int> FilterDigitsImpl(IEnumerable<int> numbers, byte digit)

        foreach (int number in numbers)

        if (number.ContainsDigit(digit))

        yield return number;





        If your version of C# is recent enough, you can merge both methods using local functions:



        public static IEnumerable<int> FilterDigits(IEnumerable<int> numbers, byte digit)

        if (numbers == null)

        throw new ArgumentNullException();


        IEnumerable<int> FilterDigitsImpl()

        foreach (int number in numbers)

        if (number.ContainsDigit(digit))

        yield return number;




        return FilterDigitsImpl();






        share|improve this answer













        Your method is an enumerable built using yield return. What's tricky about it is that nothing will actually happen unless you enumerate it.



        So you must make sure that your test enumerates the contents:



         [Test]
        public void FilterDigits_NullNumbers_ArgumentNullException()
        => Assert.Throws<ArgumentNullException>(() => DigitsFilter.FilterDigits(null, 5).ToList());


        Also, your second test will fail either way because you won't reach ContainsDigit if numbers is empty.



        If you want to fix the behavior inside of the method, you need to cut it into two:



        public static IEnumerable<int> FilterDigits(IEnumerable<int> numbers, byte digit)

        if (numbers == null)

        throw new ArgumentNullException();


        return FilterDigitsImpl(numbers, digit);


        private static IEnumerable<int> FilterDigitsImpl(IEnumerable<int> numbers, byte digit)

        foreach (int number in numbers)

        if (number.ContainsDigit(digit))

        yield return number;





        If your version of C# is recent enough, you can merge both methods using local functions:



        public static IEnumerable<int> FilterDigits(IEnumerable<int> numbers, byte digit)

        if (numbers == null)

        throw new ArgumentNullException();


        IEnumerable<int> FilterDigitsImpl()

        foreach (int number in numbers)

        if (number.ContainsDigit(digit))

        yield return number;




        return FilterDigitsImpl();







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 23 at 19:55









        Kevin GosseKevin Gosse

        34.2k35473




        34.2k35473





























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55317634%2fassert-throws-method-doesnt-catch-the-expected-exception%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

            SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

            은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현