none
Extension Method Not Found RRS feed

  • Question

  • I am writing unit tests. And this there is an issue:

    Here the Test:

    namespace TestDataServices.Shared
    {
        [TestClass]
        public class TestCustomExtensions
        {
            [TestMethod]
            public void TestStringExtNullIfEmpty_Null()
            {
                String str = null;
                Assert.IsNull(str.NullIfEmpty());
            }
        }
    }
    

    But it fails with this error message:

    'string' does not contain a definition for 'NullIfEmpty' and no extension method

    'NullIfEmpty' accepting a first argument of type 'string' could be found

    (are you missing a using directive or an assembly reference?)

    Here is the Extension method:

    namespace CustomExtensions
    {
        public static class StringExtension
        {
            public static String NullIfEmpty(this String str)
            {
                if (str != null)
                    str = str.Trim();
                if (String.IsNullOrEmpty(str))
                {
                    str = null;
                }
                return str;
            }
        }
    }
    

    This extension method works through out the code just not in the unit test.

    BTW, the tests are all in a separate project called TestDataServices. And it has a reference to the project which has the CustomExtensions.

    Can somebody tell me why I am getting that error?

    Thanks

    Eric

    Tuesday, October 23, 2012 4:55 PM

Answers

  • Accordingto what you show, the namespace for the extension is CustomExtensions, not MrdDataServices.Shared.  Therefore the using statement should be using CustomExtensions;.

    Jose R. MCP
    Code Samples

    • Marked as answer by Eric Coffman Tuesday, October 23, 2012 5:09 PM
    Tuesday, October 23, 2012 5:01 PM

All replies

  • The test project must reference the project/module where the extension resides and it must import its namespace using a using statement.

    Jose R. MCP
    Code Samples

    Tuesday, October 23, 2012 4:57 PM
  • Yes, I have this using:

    using MrdDataServices.Shared;

    And, under TestDataServices References, there is MrdDataServices.


    Tuesday, October 23, 2012 4:59 PM
  • Accordingto what you show, the namespace for the extension is CustomExtensions, not MrdDataServices.Shared.  Therefore the using statement should be using CustomExtensions;.

    Jose R. MCP
    Code Samples

    • Marked as answer by Eric Coffman Tuesday, October 23, 2012 5:09 PM
    Tuesday, October 23, 2012 5:01 PM