2
votes

I have used Nunit framework to write Unit test for ServiceStack apis. code as below

public class AppHost : AppHostBase
{
    public AppHost()
        : base("SearchService", typeof(SearchService).Assembly)
    {

    }
}

Service class as below

public class SearchService:Service
{
   public SearchResponse Get(SearchRequest request)
   { 
     // to stuff
     Response.StatusCode = (int)HttpStatusCode.OK;
     return SearchReponse;
   }
}

unit test class as below

 [TestFixture]
public class SearchServiceTests
{
    private readonly ServiceStackHost appHost;

    public SearchServiceTests()
    {
        appHost = new BasicAppHost(typeof(SearchService).Assembly)
        {
        }.Init();

    }
     [TestFixtureTearDown]
    public void TestFixtureTearDown()
    {
        appHost.Dispose();
    }


    [Test]

    public void TestMethod1()
    {
        var service = appHost.Container.Resolve<SearchService>();

        var r= service.Get(new SearchRequest());

       Assert.That(r, Is.Not.Null);

    }
    }

I am getting null reference exception for Response object. When I hit server using any client (postman or rest client) that response object is getting initialised but through unit test Response object is not getting initialised, can anyone tell me why is it happening? Thanks in advance.

1

1 Answers

5
votes

need to mock request object .so that service layer will initialise response object.

following code change worked for me.

   var service = appHost.Container.Resolve<SearchService>();
        service.Request = new MockHttpRequest(); 

then make service method call.