5

我正在使用 ServiceStack / StructureMap / Moq。该服务调用类型为 ServiceStack.CacheAccess.ISession 的 Session。对于单元测试,我使用 Moq 创建了一个 Mock 对象,并将其添加到 StructureMap 配置中:

protected Mock<ISession> sessionMock = new Mock<ISession>();
ObjectFactory.Configure(
    cfg =>
       {
           cfg.For<ISession>().Use(sessionMock.Object);

但是,当 Session 对象为 null 时,我并不感到惊讶——我很确定我遗漏了一步。我还需要做什么才能用模拟对象填充我的 Session 属性?

[编辑] 这是一个简单的测试场景

要测试的代码。简单的请求/服务

[Route("getKey/{key}")]
public class MyRequest:IReturn<string>
{
    public string Key { get; set; }
}

public class MyService:Service
{
    public string Get(MyRequest request)
    {
        return (string) Session[request.Key];
    }
}

基础测试类和 MockSession 类

// test base class
public abstract class MyTestBase : TestBase
{
    protected IRestClient Client { get; set; }

    protected override void Configure(Container container)
    {
        // this code is never reached under any of my scenarios below
        container.Adapter = new StructureMapContainerAdapter();
        ObjectFactory.Initialize(
            cfg =>
                {
                    cfg.For<ISession>().Singleton().Use<MockSession>();
                });
    }
}

public class MockSession : ISession
{
    private Dictionary<string, object> m_SessionStorage = new Dictionary<string, object>();

    public void Set<T>(string key, T value)
    {
        m_SessionStorage[key] = value;
    }

    public T Get<T>(string key)
    {
        return (T)m_SessionStorage[key];
    }

    public object this[string key]
    {
        get { return m_SessionStorage[key]; }
        set { m_SessionStorage[key] = value; }
    }
}

和测试。请参阅我在哪里看到失败的评论。我真的没想到版本 1 和 2 可以工作,但希望版本 3 可以。

[TestFixture]
public class When_getting_a_session_value:MyTestBase
{
    [Test]
    public void Test_version_1()
    {
        var session = ObjectFactory.GetInstance<MockSession>();
        session["key1"] = "Test";
        var request = new MyRequest {Key = "key1"};
        var client = new MyService();  // generally works fine, except for things like Session
        var result = client.Get(request);  // throws NRE inside MyService
        result.ShouldEqual("Test");
    }

    [Test]
    public void Test_version_2()
    {
        var session = ObjectFactory.GetInstance<MockSession>();
        session["key1"] = "Test";
        var request = new MyRequest {Key = "key1"};
        var client = ObjectFactory.GetInstance<MyService>();
        var result = client.Get(request);  // throws NRE inside MyService
        result.ShouldEqual("Test");
    }
    [Test]
    public void Test_version_3()
    {
        var session = ObjectFactory.GetInstance<MockSession>();
        session["key1"] = "Test";
        var request = new MyRequest {Key = "key1"};
        var client = CreateNewRestClient();
        var result = client.Get(request);  // throws NotImplementedException here
        result.ShouldEqual("Test");
    }
}
4

1 回答 1

9

看起来您正在尝试创建单元测试,但您正在使用 AppHost,就像您进行集成测试一样。有关两者之间的差异以及有关测试的文档,请参阅此先前的答案。

您可以通过在 中注册一个实例来模拟 Session Request.Items["__session"],例如:

[Test]
public void Can_mock_IntegrationTest_Session_with_Request()
{
    using (new BasicAppHost(typeof(MyService).Assembly).Init())
    {
        var req = new MockHttpRequest();
        req.Items[SessionFeature.RequestItemsSessionKey] = 
            new AuthUserSession {
                UserName = "Mocked",
            };

        using (var service = HostContext.ResolveService<MyService>(req))
        {
            Assert.That(service.GetSession().UserName, Is.EqualTo("Mocked"));
        }
    }
}

否则,如果您设置AppHost.TestMode=trueServiceStack 将返回IAuthSession在您的 IOC 中注册的内容,例如:

[Test]
public void Can_mock_UnitTest_Session_with_IOC()
{
    var appHost = new BasicAppHost
    {
        TestMode = true,
        ConfigureContainer = container =>
        {
            container.Register<IAuthSession>(c => new AuthUserSession {
                UserName = "Mocked",
            });
        }
    }.Init();

    var service = new MyService {
        Request = new MockHttpRequest()
    };
    Assert.That(service.GetSession().UserName, Is.EqualTo("Mocked"));

    appHost.Dispose();
}
于 2013-02-21T21:10:30.583 回答