Dependency injection for NServiceBus Saga unit testing - testing

My question is similar to question about DI for NserviceBus Handler for testing (Handler).
As a solution, you can use constructor injection by using the following syntax:
Test.Handler<YourMessageHandler>(bus => new YourMessageHandler(dep1, dep2))
I couldn't find a way to use the same approach for Saga testing.
There is a support for property injecting, which would look something like this:
var saga = Test.Saga<MySaga>()
.WithExternalDependencies(DependenciesSetUp);
private void DependenciesSetUp(MySaga saga)
{
saga.M2IntegrationService = M2IntegrationService.Object;
saga.ProcessLogService = ProcessLogService.Object;
saga.Log = Log.Object;
}
However, this approach requires making my dependencies public properties. And I want to try to avoid it.
Is there a way to use construction dependency injection for Saga testing?

You can work around this like:
Have a saga that has a constructor with parameters (in addition to a default empty constructor, which is required).
This is how your test can look like:
Test.Initialize();
var injected = new InjectedDependency() {Id = Guid.NewGuid(), SomeText = "Text"};
var testingSaga = new MySaga(injected);
var saga = Test.Saga(testingSaga);
saga.WhenReceivesMessageFrom("enter code here")
Will this work for you?

Yes it is also supported:
var saga = new MySaga(new MyFirstDep(), new MySecondDep());
Test.Saga(saga)
.ExpectSend<ProcessOrder>(m => m.Total == 500)
.ExpectTimeoutToBeSetIn<SubmitOrder>((state, span) => span == TimeSpan.FromDays(7))
.When(s => s.Handle(new SubmitOrder
{
Total = 500
}));

Related

Test Dependency Injection scope "coherence" with xUnit

In an AzureFunction, I register some services as scoped and some other as Singleton.
It turned out that a dependency of a Singleton was a Scoped service (a bad thing) and at runtime I get this kind of exception.
I would like to be able to write an unit test to check the same thing as the runtime but I did not manage to succeed. Anyone can help me ?
What I tried:
// Arrange
var functionStartup = new MyFunctionStartup();
var serviceCollection = new ServiceCollection();
var functionHostBuilder = A.Fake<IFunctionsHostBuilder>();
A.CallTo(() => functionHostBuilder.Services).Returns(serviceCollection);
// Act
// doing in fact under the hood:
// services.AddSingleton<ISingleton, Singleton>();
// services.AddScoped<IScopedDependencyOfSingleton, ScopedDependencyOfSingleton>();
functionStartup.Configure(functionHostBuilder);
// Assert
var provider = serviceCollection.BuildServiceProvider();
var singleton = provider.GetService<ISingleton>();
You can get an underlying DryIoc IContainer from the service provider and Validate for the captive dependency in a singleton:
var container = provider.GetRequiredService<IContainer>();
var errors = container.Validate(ServiceInfo.Of<ISingleton>());
if (errors.Count > 0)
{
// handle errors
}
Here is the documentation for Validate.

Using UserManager not working inside Timer

In my project I am trying to get a user based on it's email adress every second with the UserManager but when I do this I get the following error Cannot access a disposed object Object name: 'UserManager1, but this is when I do it inside of a Timer(). If I just do it once there is no problem, how can I fix this? This timer is inside a class that is being called by a SignalR Hub.
Code:
Timer = new System.Threading.Timer(async (e) =>
{
IEnumerable<Conversation> conversations = await _conversationsRepo.GetAllConversationsForUserEmailAsync(userMail);
List<TwilioConversation> twilioConversations = new List<TwilioConversation>();
foreach (Conversation conversation in conversations)
{
TwilioConversation twilioConversation = await _twilioService.GetConversation(conversation.TwilioConversationID);
twilioConversation.Messages = await _twilioService.GetMessagesForConversationAsync(conversation.TwilioConversationID);
twilioConversation.ParticipantNames = new List<string>();
List<TwilioParticipant> participants = await _twilioService.GetParticipantsForConversationAsync(conversation.TwilioConversationID);
foreach (TwilioParticipant participant in participants)
{
User user = await _userManager.FindByEmailAsync(participant.Email);
twilioConversation.ParticipantNames.Add(user.Name);
}
twilioConversations.Add(twilioConversation);
}
}, null, startTimeSpan, periodTimeSpan);
UserManager along with quite a few other types is a service that has a scoped lifetime. This means that they are only valid within the lifetime of a single request.
That also means that holding on to an instance for longer is not a safe thing to do. In this particular example, UserManager depends on the UserStore which has a dependency on a database connection – and those will definitely be closed when the request has been completed.
If you need to run something outside of the context of a request, for example in a background thread, or in your case in some timed execution, then you should create a service scope yourself and retrieve a fresh instance of the dependency you rely on.
To do that, inject a IServiceScopeFactory and then use that to create the scope within your timer code. This also applies to all other scoped dependencies, e.g. your repository which likely requires a database connection as well:
Timer = new System.Threading.Timer(async (e) =>
{
using (var scope = serviceScopeFactory.CreateScope())
{
var conversationsRepo = scope.ServiceProvider.GetService<ConversionsRepository>();
var userManager = scope.ServiceProvider.GetService<UserManager<User>>();
// do stuff
}
}, null, startTimeSpan, periodTimeSpan);

Build/Test verification for missing implementations of query/commands in MediatR

We're using MediatR heavily in our LoB application, where we use the command & query pattern.
Often, to continue in development, we make the commands and the queries first, since they are simple POCOs.
This sometimes can lead to forgetting to create an actual command handler/query handler. Since there's no compile-time validation if there is actually an implementation for the query/command, I was wondering what would be the best approach to see if there's an implementation and throw an error if not, before being able to merge into master.
My idea so far:
Create a two tests, one for queries and one for commands, that scan all the assemblies for an implementation of IRequest<TResponse>, and then scan the assemblies for an associated implementation of IRequestHandler<TRequest, TResponse>
But this would make it still required to first execute the tests (which is happening in the build pipeline), which still depends on the developer manually executing the tests (or configuring VS to do so after compile).
I don't know if there's a compile-time solution for this, and even if that would be a good idea?
We've gone with a test (and thus build-time) verification;
Sharing the code here for the actual test, which we have once per domain project.
The mediator modules contain our query/command(handler) registrations, the infrastructure modules contain our handlers of queries;
public class MissingHandlersTests
{
[Fact]
public void Missing_Handlers()
{
List<Assembly> assemblies = new List<Assembly>();
assemblies.Add(typeof(MediatorModules).Assembly);
assemblies.Add(typeof(InfrastructureModule).Assembly);
var missingTypes = MissingHandlersHelpers.FindUnmatchedRequests(assemblies);
Assert.Empty(missingTypes);
}
}
The helper class;
public class MissingHandlersHelpers
{
public static IEnumerable<Type> FindUnmatchedRequests(List<Assembly> assemblies)
{
var requests = assemblies.SelectMany(x => x.GetTypes())
.Where(t => t.IsClass && t.IsClosedTypeOf(typeof(IRequest<>)))
.ToList();
var handlerInterfaces = assemblies.SelectMany(x => x.GetTypes())
.Where(t => t.IsClass && (t.IsClosedTypeOf(typeof(IRequestHandler<>)) || t.IsClosedTypeOf(typeof(IRequestHandler<,>))))
.SelectMany(t => t.GetInterfaces())
.ToList();
List<Type> missingRegistrations = new List<Type>();
foreach(var request in requests)
{
var args = request.GetInterfaces().Single(i => i.IsClosedTypeOf(typeof(IRequest<>)) && i.GetGenericArguments().Any() && !i.IsClosedTypeOf(typeof(ICacheableRequest<>))).GetGenericArguments().First();
var handler = typeof(IRequestHandler<,>).MakeGenericType(request, args);
if (handler == null || !handlerInterfaces.Any(x => x == handler))
missingRegistrations.Add(handler);
}
return missingRegistrations;
}
}
If you are using .Net Core you could the Microsoft.AspNetCore.TestHost to create an endpoint your tests could hit. Sort of works like this:
var builder = WebHost.CreateDefaultBuilder()
.UseStartup<TStartup>()
.UseEnvironment(EnvironmentName.Development)
.ConfigureTestServices(
services =>
{
services.AddTransient((a) => this.SomeMockService.Object);
});
this.Server = new TestServer(builder);
this.Services = this.Server.Host.Services;
this.Client = this.Server.CreateClient();
this.Client.BaseAddress = new Uri("http://localhost");
So we mock any http calls (or any other stuff we want) but the real startup gets called.
And our tests would be like this:
public SomeControllerTests(TestServerFixture<Startup> testServerFixture)
: base(testServerFixture)
{
}
[Fact]
public async Task SomeController_Returns_Titles_OK()
{
var response = await this.GetAsync("/somedata/titles");
response.StatusCode.Should().Be(HttpStatusCode.OK);
var responseAsString = await response.Content.ReadAsStringAsync();
var actualResponse = Newtonsoft.Json.JsonConvert.DeserializeObject<IEnumerable<string>>(responseAsString);
actualResponse.Should().NotBeNullOrEmpty();
actualResponse.Should().HaveCount(20);
}
So when this test runs, if you have not registered your handler(s) it will fail! We use this to assert what we need (db records added, response what we expect etc) but it is a nice side effect that forgetting to register your handler gets caught at the test stage!
https://fullstackmark.com/post/20/painless-integration-testing-with-aspnet-core-web-api

Rhino Mock 3.6 Repository Expected #0, Actual#1

I'm using Rhino Mock 3.6 Repository and Nhibernate. But I'm getting ExpectationViolationException Expected#0, Actual #1. I've spent two days on it. I don't know what i'm doing wrong. Here is my code. I'm getting error on mockRepository.Save(user) line.
var username = "abcdef";
var mocks = new MockRepository();
var validationResults = new ValidationResults();
IDataQuery query = mocks.StrictMock<IDataQuery>();
UserRepository mockRepository = mocks.StrictMock<UserRepository>(query);
var user = mocks.StrictMock<User>();
user.FirstName = "javed";
user.LastName = "ahmad";
user.UserName = "abc";
user.Password = "password";
user.Email = "nadeem#test.com";
user.IsActive = true;
user.CreatedBy = 1000000;
user.CreatedDate = DateTime.Today;
user.ModifiedBy = 1000000;
user.ModifiedDate = DateTime.Today;
Expect.Call(user.Validate()).Return(validationResults);
mocks.ReplayAll();
mockRepository.Save(user);
Thanks in Advance.
Thanks
Imran
You're using a StrickMock which means the only calls to be considered valid are the calls you set Expectations for. Since you didn't set an Expectation that Save would be called, you're getting an error.
Normally this means RhinoMock expects you to call user.Validate() once, but you call the method twice. You can either check that you call the method only once or change
Expect.Call(user.Validate()).Return(validationResults);
to
Expect.Call(user.Validate()).Return(validationResults).Repeat.Twice();
You appear to be mocking everything even the sut i.e. userrepository
you should be setting up mocks on interfaces that will be used inside the userrepository. you will need to pass these in to the userrepository to override their default behaviour somehow.
You need to decide what you actually want to test.
The code above implies the following to me
class UserRepository
{
public void Save(IUser user)
{
validationResult = user.Validate();
if (validationResult==null)
{
dal.Save(user);
}
}
}
That's just a guess, but the point is the code you currently have should only be mocking the user if your intention is to test that the validate method is called within the userrepository.save method

Rhino AutoMocker and Stubs

I am using Joshua Flanagan article “Auto mocking Explained” as a guide. In the article there is a section called “The same tests, with automocker would look like this”. I used this information to build code to run the automocker.
As you can see below answer is a list returned from the BLL. Answer does have one row in it; however, all fields are null. So the test for boo fails. Any tips and hints would be greatly appreciated.
[Test]
public void GetStaffListAndRolesByTeam_CallBLLWithDALStub()
{
// Build List<> data for stub
List<StaffRoleByTeamCV> stubData = new List<StaffRoleByTeamCV>();
StaffRoleByTeamCV stubRow = new StaffRoleByTeamCV();
stubRow.Role = "boo";
stubRow.StaffId = 12;
stubRow.StaffName = "Way Cool";
stubData.Add(stubRow);
// create the automocker
var autoMocker = new RhinoAutoMocker<PeteTestBLL>();
// get instance of test class (the BLL)
var peteTestBllHdl = autoMocker.ClassUnderTest;
// stub out call to DAL inside of BLL
autoMocker.Get<IPeteTestDAL>().Stub(c => c.GetStaffListAndRolesByTeam("4146")).Return(stubData);
// make call to BLL this should return stubData
List<StaffRoleByTeamCV> answer = peteTestBllHdl.GetStaffListAndRolesByTeam("4146");
// do simple asserts to test stubData present
// this passes
Assert.IsTrue(1 == answer.Count, "Did not find any rows");
// this fails
Assert.IsTrue(answer[0].Role == "boo", "boo was not found");
}
I tried using MockMode.AAA but still no joy
An new version of AutoMocker (1.0.3) is available. The new version supports relay mode as in this example..
[TestMethod]
public void ShouldSupportOrderedTest()
{
//Arrange
var autoMocker = new RhinoAutoMocker<CustomerUpdater>();
var mockRepository = autoMocker.Repository;
using (mockRepository.Ordered())
{
autoMocker.Get<ICustomerDataProvider>().Expect(x => x.GetCustomer(Arg<int>.Is.Anything)).Return(new CustomerItem());
autoMocker.Get<ICustomerDataProvider>().Expect(x => x.UpdateCustomer(Arg<CustomerItem>.Is.Anything));
autoMocker.Get<ILogWriter>().Expect(x => x.Write(Arg<string>.Is.Anything));
autoMocker.Get<ILogWriter>().Expect(x => x.Write(Arg<string>.Is.Anything));
autoMocker.Get<IMailSender>().Expect(x => x.SendMail(Arg<string>.Is.Anything, Arg<string>.Is.Anything));
}
//Act
autoMocker.ClassUnderTest.UpdateCustomerName(1, "Frank", "frank#somecompany.com");
//Assert
ExceptionAssert.Throws<ExpectationViolationException>(mockRepository.VerifyAll,"IMailSender.SendMail(anything, anything); Expected #1, Actual #0.\r\nILogWriter.Write(anything); Expected #1, Actual #0.\r\n");
}
I haven't tried, but this article suggests that by default all the mocks created by automocker are not replayed:
http://www.lostechies.com/blogs/joshuaflanagan/archive/2008/09/25/arrange-act-assert-with-structuremap-rhinoautomocker.aspx
Yes that was true for the previous version. But was changed to support ordered tests in version 1.0.3.