abp icon indicating copy to clipboard operation
abp copied to clipboard

Unit test an application service by injecting an ObjectMapper mock

Open Stirda opened this issue 6 years ago • 5 comments

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.

Stirda avatar May 01 '20 14:05 Stirda

You can use dependency injection to replace IObjectMapper in test projects.

realLiangshiwei avatar May 01 '20 14:05 realLiangshiwei

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.

Stirda avatar May 01 '20 15:05 Stirda

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.

realLiangshiwei avatar May 01 '20 15:05 realLiangshiwei

By converting this private attribute to protected I don't see breaking changes. Even by adding a constructor.

Stirda avatar May 06 '20 11:05 Stirda

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.

Stirda avatar May 08 '20 08:05 Stirda