0

I want to test WebMethod of some Web Service (asmx). Suppose I have the following code:

    public IUsersRepository UsersRepository
    {
        get { return Session["repository"] as IUsersRepository; }
        set { Session["repository"] = value; }
    }

    [WebMethod(EnableSession = true)]
    public int AddUser(string userName, int something)
    {
        var usersRepository = Session["repository"] as IUsersRepository;
        return usersRepository.AddUser(userName, something);
    }

and the corresponding unit test (just to test that the repository is called at all):

    [Test]
    public void add_user_adds_user()
    {
        // Arrange
        var repository = new Mock<IUsersRepository>();
        var service = new ProteinTrackingService { UsersRepository = repository.Object };

        // Act
        var userName = "Tester";
        var something = 42;
        service.AddUser(userName: userName, something: something);

        // Assert
        repository.Verify(r => r.AddUser(
            It.Is<string>(n => n.Equals(userName)),
            It.Is<int>(p => p.Equals(something))));
    }

When I run this test, I receive the following error message:

System.InvalidOperationException : HttpContext is not available.
This class can only be used in the context of an ASP.NET request.

What shall I do to make this test working?

Old Fox
  • 8,191
  • 4
  • 29
  • 48
user2341923
  • 3,921
  • 4
  • 23
  • 38
  • In production the IIS server initialize the context. In UT you have to initialize it manually... – Old Fox Dec 26 '15 at 14:11

1 Answers1

1

Have you had a look at this one? Setting HttpContext.Current.Session in a unit test Apparently should can do that trick to simulate your session.

On regards to your assert, you can directly do:

// Assert
    repository.Verify(r => r.AddUser(userName, something));

And that will assert you are calling that method with these parameters.

Hope this helps!

Community
  • 1
  • 1
Carlos Torrecillas
  • 3,402
  • 4
  • 23
  • 52