﻿# Uniform Session Testing

<!-- Version variant: uniformsessiontesting_4; default: [/nservicebus/messaging/uniformsession-testing.md](/nservicebus/messaging/uniformsession-testing.md) -->


Shows the usage of the `NServiceBus.UniformSession.Testing` package.

## Prerequisites for uniform session testing functionality

The approach shown here works with the `NServiceBus.UniformSession` NuGet package version 2.2.0 or above. Install the `NServiceBus.UniformSession.Testing` NuGet package.

> [!NOTE]
> The fluent-style test APIs have been deprecated. See the [Testing Upgrade Guide](/nservicebus/upgrades/testing-7to8.md) for more information.

### Testing services

Construct the service under test with an instance of `TestableUniformSession`. Call the methods being tested and make assertions about the messages sent and published.

<!-- snippet: UniformSessionServiceTesting -->

```cs
var session = new TestableUniformSession();
var service = new SomeService(session);

service.DoTheThing();

Assert.AreEqual(1, session.SentMessages.Length);
```

<!-- endsnippet -->

### Testing together with IMessageSession

For tests including code paths using both `IMessageSession` and `IUniformSession`, the `TestableUniformSession` can also wrap a `TestableMessageSession`:

<!-- snippet: UniformSessionMessageSessionTesting -->

```cs
var messageSession = new TestableMessageSession();
// pass the message session to the TestableUniformSession:
var uniformSession = new TestableUniformSession(messageSession);
var sharedComponent = new SharedComponent(uniformSession);
var myService = new MyService(sharedComponent);

myService.Start(messageSession);

Assert.AreEqual(1, messageSession.PublishedMessages.Length);
```

<!-- endsnippet -->

### Testing a handler

Construct the handler under test with an instance of `TestableUniformSession`.

<!-- snippet: UniformSessionHandlerTesting -->

```cs
var handlerContext = new TestableMessageHandlerContext();
// pass the handler context to TestableUniformSession:
var uniformSession = new TestableUniformSession(handlerContext);
var handler = new SomeMessageHandler(new SharedComponent(uniformSession));

await handler.Handle(new SomeEvent(), handlerContext);

Assert.AreEqual(1, uniformSession.SentMessages.Length);
```

<!-- endsnippet -->

### Testing a saga

Construct the saga under test with an instance of `TestableUniformSession`.

<!-- snippet: UniformSessionSagaTesting -->

```cs
var handlerContext = new TestableMessageHandlerContext();
var uniformSession = new TestableUniformSession(handlerContext);
var saga = new SomeSaga(uniformSession);

saga.Handle(new SomeMessage(), handlerContext);

Assert.AreEqual(1, uniformSession.PublishedMessages.Length);
```

<!-- endsnippet -->
