Unit test an application service by injecting an ObjectMapper mock
I succeded in unit testing one of my application services by injecting an ObjectMapper mock. But I had to rewrite Volo.Abp.Application.Services.ApplicationService either changing protected IObjectMapper _objectMapper into private or addind a constructor with an additional IObjectMapper parameter.
The problem is I had to duplicate ApplicationService source code into a TestableApplicationService, with this very little modification which is very bad. Nothing overridable was suitable.
Could Volo.Abp.Application.Services.ApplicationService offer this testing ability out-of-the-box ?
Side note: You may ask you why I unit test my application service. I know that integrated tests are more simple to code but they are much slower.
You can use dependency injection to replace IObjectMapper in test projects.
In integrated tests, yes. But in a unit test, I don't think so. The purpose of an unit test is to depend only on the class under test and possibly some dependant interfaces. Dependency injection is activated during ABP modules start. A unit test doesn't run all of that.
If so, do we need to change services such as IGuidGenerator, ICurrentTenant, ISettingProvider etc to constructor injection?
I think it's a break change. You should customize the application service base class for your needs.
By converting this private attribute to protected I don't see breaking changes. Even by adding a constructor.
I finally found a solution neither modifying Volo.Abp.Application.Services.ApplicationService nor the template. I found that I can mock the ServiceProvider property:
// Arrange
var objectMapper = Substitute.For<IObjectMapper>();
// << Insert here IObjectMapper mock wanted behavior >>
var currentUser = Substitute.For<ICurrentUser>();
// << Insert here ICurrentUser mock wanted behavior >>
var authorizationService = Substitute.For<IAbpAuthorizationService>();
// << Insert here IAbpAuthorizationService mock wanted behavior >>
var serviceProvider = Substitute.For<IServiceProvider>();
serviceProvider.GetService(typeof(IObjectMapper))
.Returns(objectMapper);
serviceProvider.GetService(typeof(ICurrentUser))
.Returns(currentUser);
serviceProvider.GetService(typeof(IAuthorizationService))
.Returns(authorizationService);
var myAppServiceUnderTest
= new MyAppService()
{
ServiceProvider = serviceProvider
};
Now I get clean application services unit testing 👍 And fast.