Unit test method for Wcf service throws System.NullReferenceException RRS feed

  • Question

  • I am unit testing a WCF service methods.

    When I creat a unit test, the default code for creating a service object is added as:

    MyService target = new MyService();

    But when i run the test, it throws following exception at the above line itself:

    System.NullReferenceException: Object reference not set to an instance of an object..

    I have service reference added to UnitTest Project.

    Can someone help me on this?

    Friday, January 27, 2012 1:52 PM

All replies

  • Hi,

    Poleh wrote a blog about the unit testing WCF Services, see http://blogs.msdn.com/b/ploeh/archive/2006/12/03/unittestingwcfservices.aspx


    Monday, January 30, 2012 10:39 AM
  • Hi,

    Thanks for the link.

    I have already added a service reference to unit testing project and access the service to be tested in following manner.




    public void IsAccountAvailableWCFTest()



    MyServiceClient target = new MyService.MyServiceClient();


    string AccountID = Helper.AccountId;


    bool expected = true;


    bool actual;




    actual = target.IsAccountAvailable(AccountID);


    Assert.AreEqual(expected, actual);



    catch (FaultException faultEx)



    Assert.Fail(Helper.ExceptionMessage + ":" + faultEx.ToString());



    This code now works fine for me only for the public methods and those who are exposed through interface.

    Now i wish to unit test the private method from service class.







    public void WriteLogWCFTest()



    MyService_Accessor target = new MyService_Accessor(); // TODO: Initialize to an appropriate value


    string log = string.Empty;

    // TODO: Initialize to an appropriate value


    bool expected = true





    // Rest test code lies here.


    But i am unable to access private method using service accessor.

    test case fails at line MyService_Accessor target = new MyService_Accessor(); and thows exception

    System.NullReferenceException: Object reference not set to an instance of an object..

    Since it is a private method i would never be able to access it through client proxy.

    So how do i test private method in WCF?

    Monday, January 30, 2012 12:44 PM
  • Private accessors are not supported and is a deprecated feature. Limited work-arounds are provided at the following link:


    Trevor Hancock (Microsoft)
    Please remember to "Mark As Answer" the replies that help.

    Tuesday, February 7, 2012 5:37 PM