简体   繁体   中英

Unit Testing Web Service Session variable with NUnit and Moq

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?

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM