UnitTesting static Class (Theoretical Question) - c#

I know when is ok to use a Static Class, but my simple question is:
If there's a big problem when we're Unit-Testing our code that has some Static Class?
Is better just using a regular instances class?
Thanxs (i know there's some questions that talk about this, but all are based in particular case I just want to have a general opinion about it)

What I do is take the existing static class use as a seam, and provide an alternative implementation in a different namespace. This means that you can get the code under test with as few changes as possible -- just namespace changes. Typically I've had to do this to get round C# filesystem ops -- File.Exists etc.
Say your method basically does this:
using System.IO;
public void SomeMethod()
{
...
if(File.Exists(myFile))
{
...
}
...
}
then I'd replace that implementation of File with an alternative. The alterntive implementation should stub out any existing methods, and make calls to delegate implementations under the covers -- e.g.
namespace IO.Abstractions
{
public static class File
{
public static Func<string, string, string> ExistsImpl =
System.IO.File.Exists;
public static string Exists(string path)
{
return ExistsImpl (path);
}
}
}
Then I'd modify the original code so that it uses the new namespace:
using IO.Abstractions;
public void SomeMethod()
{
...
if(File.Exists(myFile))
{
...
}
...
}
Then, in your test, you can just provide an alternative implementation of the behaviour for File.Exists, something like:
[Test]
public void SomeTest()
{
// arrange
...
File.ExistsImpl = (path) => true; // to just default to true for every call
...
// act
someClass.SomeMethod();
// then assert
...
}
I wrote a blog with some more details recently here.

Related

How can I change the behavior of a static method at runtime?

Is there a way to modify the behavior of a static method at runtime?
for example:
Say I have this class
public class Utility {
public static void DoSomething(string data){
//...
}
}
Is there a way to do something like this:
typeof(Utility).SetMethod("DoSomething", (data) => { /*Do something else...*/ });
Such that if you call Utility.DoSomething it executes the new code?
What you want to do is pass the behavior you want as another parameter into the function.
public static void DoSomething(string data, Action<string> operation)
{
operation(data);
}
This is an oversimplified example, of course. What you actually wind up doing in your own code is going to depend on what operation actually does.
If you're trying to modify the behavior of an existing, compiled, in-production method, and cannot overload or override the method in the usual ways, the only way I know of to do that is CIL Rewriting, possibly using an Aspect Weaver.
Sure.
public class Utility {
public static Action<String> _DoSomething;
public static void DoSomething(string data){
if (_DoSomething != null) {
_DoSomething();
return;
}
// default behavior here.
}
}
And to mask the default behavior:
Utility._DoSomething = (data) => { /* do something else */ };
I don't see why you wouldn't just create a new class that inherits from Utility and define a new function that does what you want.
public class Program
{
static void Main(string[] args)
{
if (true)
{
Utility.DoSomething("TEST");
} else
{
Util1.DoSomething("TEST");
}
}
}
public class Utility
{
public static void DoSomething(string data)
{
//Perform some action
}
}
abstract class Util1 : Utility
{
public static new void DoSomething(string data)
{
//Perform a different action
}
}
I think although it is possible to do this you should ask yourself: "Why do I need this functionality"? Usually a method stays as is, and does what it is supposed to do according to its interface which is given by its name and signature. So while you can add additional logic by adding an Action<T>-parameter to your signature you should ask yourself if this won´t break the contract of the interface and therefor what the method was designed for.
Having said this you should consider either overwrite your method if the functionality you need is some kind of "making the same things differently then the parent-class" or extend it by adding a dependency into your consuming class and add some methods to that class that extent the functionality provided by the contained class (see also favour composition over inheritance)
class MyClass {
Utility MyUtility;
void ExtraMethod() { /* ... */ }
}
EDIT: As you´re using a static method the opportunity on overwriting is obsolete. However IMO that sounds like a great design-flaw.

Can a Roslyn Code Fix operate on multiple independent call sites?

I'd like to create a Roslyn code fix that changes attributed code such as this:
public class CommandHandler
{
[Command("Cmd1")]
public void Foo()
{
// do something
}
[Command("Cmd2")]
public void Bar()
{
// do something
}
}
to this:
public class CommandHandler
{
public void Foo()
{
// do something
}
public void Bar()
{
// do something
}
public void Execute(string command)
{
switch(command)
{
case "Cmd1":
Foo();
break;
case "Cmd2":
Bar();
break;
}
}
}
The main requirements are:
The signature for the refactoring is any method attributed with the [Command] attribute.
There can be multiple such methods in a class.
The synthesized Execute() method must preserve existing cases and add new ones.
Is it possible to create such a refactoring such that I can ask it to fix all instances in a project at one go? This is a feasibility question, to help me avoid running into a dead end, if there is one.
I would use analyzer + code fix provider for this.
The analyzer examines nodes of SyntaxKind.Attribute kind and reports a diagnostic if the attribute matches your CommandAttribute type.
The code fix provider provides both RegisterCodeFixesAsync to refactor a single attribute and a custom FixAllProvider that can refactor all attributes in a document/project/solution.
This way VS does all the heavy lifting and your code fix provider automatically gets list of all the attributes in the scope you're interested in.

How to stub a static method?

I am working on a brownfield application and am currently refactoring part of it. I am trying to do this in a TDD fashion but am running into a problem. Part of the code I am testing does
var siteLanguages = from sl in SiteSettings.GetEnabledSiteLanguages() select sl.LanguageID;
where GetEnabledLanguages has the following signature
public static List<LanguageBranch> GetEnabledSiteLanguages();
it in turns calls data access code to retrieve the relevant information. Up untill now I have used a interface and DI to use a different stub implementation for these kind of dependencies during unit testing. But since the GetEnabledSiteLanguages method is static this will not work. What is the "correct" way to do it in this case?
you could create a object which implements an interface and inject an implementation of this into the class which uses the SiteSettings class. The interface declare the method with the same signature as the static method(s) you need to intercept. Then you could mock out the interface for tests and create a single implementation which delegates to the static method for the actual code:
public interface ISiteSettings
{
public List<LanguageBranch> GetEnabledSiteLanguages()
}
public class ActualSiteSettings : ISiteSettings
{
public List<LanguageBranch> GetEnabledSiteLanguages()
{
return SiteSettings.GetEnabledSiteLanguages();
}
}
... in the dependent class:
public class DependentClass
{
private ISiteSettings m_siteSettings;
public DependentClass(ISiteSettings siteSettings)
{
m_siteSettings=siteSettings;
}
public void SomeMethod
{
var siteLanguages = from sl in m_siteSettings.GetEnabledSiteLanguages() select sl.LanguageID;
}
}
What about making your method such as:
public static Func<List<LanguageBranch>> GetEnabledSiteLanguages = () => {
//your code here
};
Now it becomes first class object (as Func delegate) and a stub can replace it
Look at Moles framework.
You can use tools like JustMock, TypeMock or moles. These tools allow you to mock everythings like static methods.

Easiest way to re-use a function without instantiation a new class

I currently have a function that looks like this:
public void AnimateLayoutTransform(object ControlToAnimate)
{
//Does some stuff
}
I use this function in a lot of different projects, so I want it to be very reusable. So for now I have it in a .cs file, enclosed in a namespace and a class:
namespace LayoutTransformAnimation
{
public class LayoutAnims
{
public void AnimateLayoutTransform(object ControlToAnimate)
{
//Do stuff
}
}
}
The problem with this is that to use this one function in a given project, I have to do something like
new LayoutTransformAnimation.LayoutAnims().AnimateLayoutTransform(mygrid);
Which just seems like a lot of work to reuse a single function. Is there any way to, at the very least, use the function without creating a new instance of the class? Similar to how we can Double.Parse() without creating a new double?
One option is to make it a normal static method. An alternative - if you're using C# 3.0 or higher - is to make it an extension method:
public static class AnimationExtensions
{
public static void AnimateLayoutTransform(this object controlToAnimate)
{
// Code
}
}
Then you can just write:
mygrid.AnimateLayoutTransform();
Can you specify the type of the control to animate any more precisely than "Object"? That would be nicer... for example, can you only really animate instances of UIElement? Maybe not... but if you can be more specific, it would be a good idea.
You could make it into a static method.
MSDN Example
I find it useful to have a static util class with static methods in them which can be used within the project namespace.
public static class YourUtilsClass
{
public static Void YourMethod()
{
//do your stuff
}
}
You can call it like so: YourUtilsClass.YourMethod()
namespace LayoutTransformAnimation
{
public class LayoutAnims
{
public static void AnimateLayoutTransform(object ControlToAnimate)
{
//Do stuff
}
}
}
LayoutTransformAnimation.LayoutAnims.AnimateLayoutTransform(something);

Finding all methods with missing security check

I am working on a code review. We have code that looks similar to this:
public int MyMethod(Message message)
{
// Check that the user has the access to the function
CheckUserHasAccessToFunction(UserName, FunctionName);
// Do the work
}
What I am wondering is: Is it possible to find all methods where the "CheckUserHasAccessToFunction" is missing. For example using regular expressions.
Which function name we test against will vary from method to method. The mapping between the function name and the method is part of the business logic, which we have implemented in code.
I think you should refactor your code in a way that you do not need to include this security check manually in every method, because - as you see - you cannot be sure if all methods perform this security check.
Have you ever worked with proxies? If so, you could add an interceptor which checks the security for you automatically. If not, tell me, then I will give you an example code snippet.
Edit: Here is a code sample which uses proxies (using Castle.DynamicProxy).
public class MyService
{
// The method must be virtual.
public virtual DoSomethingWhichRequiresAuthorization()
{
}
}
public static class MyServiceFactory
{
private static ProxyGenerator _generator;
private static ProxyGenerator Generator
{
get
{
if (_generator == null) _generator = new ProxyGenerator();
return _generator;
}
}
public static MyService Create()
{
var interceptor = new AuthorizationInterceptor();
return (MyService)Generator.CreateClassProxy(
typeof(MyService), new[] { interceptor });
}
}
public class AuthorizationInterceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
// invocation.Method contains the MethodInfo
// of the actually called method.
AuthorizeMethod(invocation.Method);
}
}
You would probably be better off using Attributes for this, in my opinion.
E.g.
[RequiresAuth]
public void Method()
{
}
I know this doesn't answer your question well, so apologies for that.

Categories

Resources