vendredi 25 décembre 2015

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 erro 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?

Aucun commentaire:

Enregistrer un commentaire