Hi,
I am trying to write plugins which should be unit testable. I have divided the plugin into 2 parts as below.
1. Plugin class - class which will get register as plugin on particular event and will have validations whether plugin should execute or not.
2. Business logic class - which contains business logic as per requirement.
I have read articles mentioning that plugin class should not have class level variables. Do you see any problem with sample code snippet of plugin class (see below) as I have created 2 constructor in plugin class. One for CRM and other to use it for unit testing?
Sample:
public class Followup: IPlugin { readonly IFollowupBusinesslogic businessLogic; //Constructor for CRM public Followup() { businessLogic = new FollowupBusinesslogic(); } //Constructor for unit testing public Followup(IFollowupBusinesslogic businessLogic) { this.businessLogic = businessLogic; } public void Execute(IServiceProvider serviceProvider) { // code.... } }
Thanks in advance!!!
*This post is locked for comments
Hi Pawel,
Thanks for good explanation.
So you have read "articles mentioning that plugin class should not have class level variables", yet you decided to create a field in your plugin class... The reason why you should not do that is that this instance of this plugin will be shared between different pipeline instances, so in this case different calls can use the same reference for your IFollowupBusinessLogic. Unless this class is stateless (which I doubt and also - you can never be sure that the next developer in your project will know that it should be stateless) this is likely going to blow off in the most unexpected moment (and probably on production, not on test environment). Believe me, that is really bad idea, so simply remove that field from Plugin class. The only place when you can instantiate your BusinessLogic class is Execute method of your plugin.
Having said that, two constructors should work, but if you have stateless plugin, it will make no sense to have them both. The way I do it is to have some kind of handler class which
a) Checks if the logic should be fired
b) Fires the logic
And the only thing I do in plugin class is to instantiate this Handler class. So I don't even write any unit test for that, because it would make totally no sense. I have total control over my Handler class, so I can write unit test for it (it can implement interface, have as many constructors as I want etc.).
Mohamed Amine Mahmoudi
83
Super User 2025 Season 1
Community Member
54
Victor Onyebuchi
6