Unit Testing Web Services - HttpContext

后端 未结 5 832
日久生厌
日久生厌 2021-01-31 00:20

I want to write unit tests for a web service. I create my test project, reference my web project (not service reference, assembly reference), then write some code to test the we

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-31 00:55

    If you are using mocking, you can wrap this logic in another class:

    interface IAuthenticator
    {
       bool IsAuthenticated();
    }
    

    and implement the real one:

    class Authenticator : IAuthenticator
    {
       bool IsAuthenticated()
       {
          return HttpContext.Current.User.Identity.IsAuthenticated;
       }
    }
    

    but in the test, create a mock and return true or false:

    Mock mock = new Mock();
    mock.Expect(x => x.IsAuthenticated()).Returns(true);
    

提交回复
热议问题