c# - Unit Testing - Session object? -
i have implemented unit of work pattern, , environment using more unit testing. implementation writes session helper writes session. how unit test these aspects in regard session? should make repository pattern? (repository interface concrete session implementation , concrete mock implementation) how done?
i know there more 1 way of approaching this, looking advice.
there 2 ways of doing this.
assuming using .net 3.5 or up. change implementation take httpsessionstatebase object constructor parameter, can mock implementation - there's few tutorials online on how this. can use ioc container wire @ app start or (poor man's dependency injection):
public class myobjectthatusessession { httpsessionstatebase _session; public myobjectthatusessession(httpsessionstatebase sesssion) { _session = session ?? new httpsessionstatewrapper(httpcontext.current.session); } public myobjectthatusessession() : this(null) {} }
alternatively, , bit better , more flexible design create test seam wrapping interaction session in object. change database, cookie or cache based implementation later. like:
public class myobjectthatusessession { istatestorage _storage; public myobjectthatusessession(istatestorage storage) { _storage= storage ?? new sessionstorage(); } public myobjectthatusessession() : this(null) {} public void dosomethingwithsession() { var = _storage.get("mysessionkey"); console.writeline("got " + something); } } public interface istatestorage { string get(string key); void set(string key, string data); } public class sessionstorage : istatestorage { //todo: refactor inject httpsessionstatebase rather using httpcontext. public string get(string key) { return httpcontext.current.session[key]; } public string set(string key, string data) { httpcontext.current.session[key] = data; } }
you can use moq create mock istatestorage implementation tests or create simple dictionary based implementation.
hope helps.
Comments
Post a Comment