How to determine ServiceStackController cache properties?

Providing the next ServiceStack controller

public class MyController : ServiceStackController 
{
    public ActionResult Index()
    {
        return View(Cache.GetAllKeys());
    }
}

and the next test class

[TestFixture]
public class MyControllerTests 
{
    [Test]
    public void Should_call_cache()
    {
        var controller = new MyController();
        // Mock here to access Cache, otherwise throws NullReferenceException
        var result = controller.Index();
        Assert.IsNotNull(result);
        var model = result.Model as IEnumerable<string>;
        Assert.IsNotNull(model);
    }
}

What is the correct way to retrieve a ICacheClientCache property to validate a validation method?

+6
source share
2 answers

UPDATE:

OP . , . (IMO) , , , -, .


Cache readonly, . , .

Cache, , .

Moq Cache.

public void _Should_call_cache() {
    //Arrange
    var controller = Mock.Of<MyController>();

    var keys = new[] { "key1", "key2", "key3" };
    var cacheMock = new Mock<ICacheClient>();
    cacheMock.Setup(_ => _.GetAllKeys()).Returns(keys);

    var mockController = Mock.Get(controller);
    mockController.CallBase = true;
    mockController.Setup(_ => _.Cache).Returns(cacheMock.Object);

    //Act
    var result = controller.Index() as ViewResult;

    //Assert
    Assert.IsNotNull(result);
    var model = result.Model as IEnumerable<string>;
    Assert.IsNotNull(model);
}

ServiceStackController.cs, , readonly .

+3

ServiceStack ServiceStack, AppHost SelfHost , , AppHost :

using (var appHost = new BasicAppHost {
        ConfigureContainer = c => ...,
    }.Init()) 
{
    // Test ServiceStack Components...
}

ConfigureContainer , ServiceStack, Cache ServiceStack MemoryCacheClient, .

+2

All Articles