Join Reynald Adolphe for an in-depth discussion in this video Unit testing static classes, part of C# Best Practices for Developers.
- So, we are ready to test our notification service. So, to do so, let's create our test project for this purpose. Right-click on Test, New Project, and we'll make sure to reselect Test on the left-hand side, and we'll call this Prestige.CommonTests. Okay, double check that it's right in the Test folder, and it seems that it is.
Let's rename this UniTest to NotificationServiceTest. Should I update my class name? Yes. Now, let me go ahead and save this, Ctrl-S, and before we move any further, we want to be able to set a reference to the project that we're going to be using.
That is Prestige.Common. And now, we can create our TestMethod. TestNotifyTalent. And when we are arranging, we'll expect, and let me go ahead and take a look to see what we wrote, talent, colon, space, and then the talent name.
Now, to make this a little bit more specific to what we're actually doing, it really should say something like Notifying talent, and then it'll have this talent name. So, I'll save that, and then over here is also what I'm going to want to display in our test. So, I'm gonna go ahead and copy and paste that into there. Notifying talent, and the value will be rey, then I'm going to pass it in.
And for the act stage, I'll specify the variable actual, and now, type in NotificationService, and I'll hold the Ctrl key down and hit the period, and import our namespace, PrestigeCommon. And at this point, if I hit period, I can invoke NotifyTalent, and I will pass in the value rey.
And for the last step, when we assert, we'll check to see if these two values are equal. That is the expected, and the actual result. So, if I right-click on TestNotifyTalent, Run Selected Test, let's see if that goes through. And it passes, great.
So, we used our notification service, and we did not have to create an instance, and that seems nice, but there are some disadvantages. Let's recap that as we talk some best practices in respect to the static class. You want to use static classes sparingly, and the main reason why is because they're meant for supporting classes. They don't really work well with object-oriented programming features. For example, they don't implement an interface. They can't have parameterized constructors, and they can't be inherited from.
So, they're good for something like common utilities. Now, something we should be avoiding is to use it as a random bucket. That is, do not use static classes as a miscellaneous bucket of methods. Every class should have a purpose, and so, its members should support that purpose, also.
- Naming and handling classes
- Running a unit test
- Using constructors
- Naming and handling methods, fields, and properties
- Using properties correctly
- Managing objects efficiently
- Common design patterns as best practices