0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

セッションは本来Controller.HttpContextに属するため、中身を見ることはできない。
しかし、確認したい場合は出てくる。ビューでセッション変数を読み込む場合だ。
そこで、以下の様なコードをテストに入れる(MSTestを利用しているが、他のフレームワークに即した形で修正すれば大丈夫なはずだ)。

[TestMethod]
public void Test()
{
    var controllerContext = new Mock<ControllerContext>();
    var session = new Mock<HttpSessionStateBase>();
    var sessionValue = string.Empty; // セッションの値を受け取る変数
    session.SetupSet(s => s["value"] = It.IsAny<object>())
        .Callback((string name, object o) => { sessionValue = (string)o; });
    controllerContext.Setup(p => p.HttpContext.Session).Returns(session.Object);

    var controller = new FooController { ControllerContext = controllerContext.Object };
    var result = contoller.Index() as ViewResult; // FooController.Index()内でSession["value"]の値が"bar"に変わると想定

    Assert.AreEqual(string.Empty, result.ViewName);
    Assert.AreEqual("bar", sessionValue);
}

参考:Tales from the Evil Empire - Mocking indexer setters with Moq

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?