This project has moved. For the latest updates, please go here.

[en] NUnit Tests of Serverside Code with reference to CurrentSession (solved)

Topics: Technical Support
Oct 26, 2013 at 1:47 PM
How can I test serverside Code that use CurrentSession-Informations without a Connection?

I have in my functions a logging statement. That stores the IP/Username in a Logentry (like: "2013-10-26 15:42 IP= - Try do delete Contact")

On my serverside Code I have much NUnit-Tests: Create a Instance of the serverside Code - execute the funtion. All these test run without a active client-server connection. So I can Check if the error on serverside or clientside (on client-Project I have different tests again)

But the CurrentSession is not set.

What can I do that my test work again? I think, that I put in every serverside Code Methode a check if CurrentSession is exists, is not the fine Art/right way?

I hope you understand and can help me
Oct 26, 2013 at 2:06 PM
Edited Oct 26, 2013 at 2:10 PM
I suggest that you wrap the code that needs to access ServerSession in a separate service.
Make all the data you need available via an interface, say, ISessionService.
Use different implementations of this interface for your production server and unit tests.

It would look something like that:
// in your shared assembly (say, Interfaces.dll):
public interface ISessionService
     string CurrentUserName { get; }
     string ClientAddress { get; }

// in your server assembly (production code):
internal class SessionService : ISessionService
     public string CurrentUserName
         // in production, current server session is always not null
         get { return ServerSession.CurrentSession.Identity.Name; }

     public string ClientAddress
         get { return ServerSession.CurrentSession.ClientAddress; }

// in your unit test assembly (mock code):
internal class MockSessionService : ISessionService
    // return fake data for unit tests
    public string CurrentUserName { get { return "Bozo"; } }
    public string ClientAddress { get { return ""; } }

// in your unit-tested service, use IoC pattern to inject the proper implementation 
// of ISessionService (using either MEF or your favorite dependency injection container):
internal class MyCodeThatNeedsCurrentSessionData
    public MyCodeThatNeedsCurrentSessionData(ISessionService service)
        Log.Info("The service is called by {0} from {1} address.", 
              service.CurrentUserName, service.ClientAddress);
Note that the last service, MyCodeThatNeedsCurrentSessionData, doesn't use ServerSession directly.
In relies on ISessionService which is always accessible.
Marked as answer by MyKey0815 on 10/29/2013 at 2:07 AM
Oct 29, 2013 at 9:07 AM
Thank you for your hint to use Mocking

I´m very new on Unit-Testing, so that technic i don´t know. But now I have learned someone new

BTW: It works fine. I use NSubtitute
Oct 29, 2013 at 10:14 AM
That's great!