NUnit - Static Vs. Public methods - c#

My project has been growing in size and in functionality so I decided to test some features using NUnit however the problem I'm facing is that most of the methods are Static, so the first thing that ocurred to me was create public methods and I am calling them from the Unit Test class however those public methods are beginning to be many, so I wonder if rather than create new Public methods inside the main class, I should create an interface or if the Static ones should be Public and be instantiated using an class intermediate.
This is an example of how my program is structured,
namespace Mynamespace
{
public class Foo
{
InsertUser();
SortUser();
}
static void InsertUser()
{
}
static void SortUser()
{
}
//Here start the public methods to be called from the unit test class
public DoSort()
{
InsertUser();
SortUser();
}
}
What's the best approach to keep separated the main logic of my program and the testing classes?
Thanks,

Instead of keeping static methods and adding non-static methods, it's better to convert all your methods from static to instance methods and extract abstraction which clients of Foo class will depend on:
public interface IFoo
{
void InsertUser();
void SortUser();
}
public class Foo : IFoo
{
void InsertUser() { ... }
void SortUser() { ... }
}
Static members introduce coupling into your application. And it's a real headache to mock static members. You should program to abstraction, instead of programing to implementation in order to make your code testable and loosely coupled. When your code depend on interface instead of static class, you can easily mock this dependency:
Mock<IFoo> fooMock = new Mock<IFoo>();
fooMock.Setup(f => f.InsertUser()).Throws<InvalidOperationException>();
var sut = new ClassUnderTest(fooMock.Object);
fooMock.VerifyAll();
And if you really need to access these methods in global scope (which is not very good idea - it's a procedural style of programming), then implement your class as Singleton:
public class Foo : IFoo
{
public static Foo Instance = new Foo(); // simple singleton implementation
private Foo() { }
void InsertUser() { ... }
void SortUser() { ... }
}
You will be able to get class instance anywhere in your application
IFoo foo = Foo.Instance;
foo.SortUser();

In my opinion, you should have your real classes and your unit classes both implementing a common interface, like this:
interface IFoo
{
void InsertUser();
void SortUser();
}
For your actual implementation, use this:
public class RealFoo : IFoo
{
public void InsertUser()
{
throw new NotImplementedException();
}
public void SortUser()
{
throw new NotImplementedException();
}
}
For your testing classes, use this:
public class FakeFoo : IFoo
{
public void InsertUser()
{
throw new NotImplementedException();
}
public void SortUser()
{
throw new NotImplementedException();
}
}
Note: Your FakeFoo class would not need to exist in the same location as your RealFoo class, but rather your IFoo interface definition should be referenced by each of the projects (one for real implementation and the other in your test project).
If your IFoo interface becomes too large (read: too many methods), then you can use the Repository Pattern, which would segment your methods into interfaces more along the lines of functionallity.

Related

CS0175 Use of keyword 'base' is not valid in this context

I am getting CS0175 Use of keyword 'base' is not valid in this context error in my unit test case project.
This is how my code looks:
A class which implements a interface
public interface iUtility
{
void Print();
}
public class Utility: iUtility
{
public void Print()
{
Console.Write("Print");
}
}
A base class which uses the utility class and a derived class
public class BaseCls
{
private iUtility _iUtility;
public BaseCls()
{
_iUtility = new Utility();
}
public BaseCls(iUtility iUtility)
{
_iUtility = iUtility;
}
}
public class DerivedCls : BaseCls
{
public void PrintSomething()
{
Console.Write("Print Something");
}
}
In my unit test project, I am testing derived class and trying to pass the instance of utility class. Why I am doing this may not make sense now but I am planning to use unity framework and use IoC to inject different dependencies.
I am not showing all code for brevity.
Error is happening in unit test project
[TestClass]
public class UnitTest1
{
public void TestInitialize()
{
//I want to pass instance of utility class here
iUtility obj = new Utility();
DerivedCls cls = new DerivedCls(): base(obj);
}
[TestMethod]
public void TestMethod1()
{
}
}
What do I need to do to fix this error? I want to pass the instance of utility class from derived class through constructor.
You need to provide a constructor in your derived class.
public class DerivedCls : BaseCls
{
public DerivedCls(iUtility utility) : base(utility) { }
}
Then construct your DerivedCls instances as you normally would: new DerivedCls(someIUtilityInstance)

C# Multiple Stub implementation for method with T

Currently I have a factory class where I have method to instantiate different classes using reflection and return a base interface which all classes implement. The code works fine in general. But when I turned to write unit test (ms-test) on the class I'm running into issues when I try to instantiate multiple classes
Factory class:
public class BusinessFactory : IBusinessFactory
{
public BusinessFactory()
{
}
public IBaseBusiness Create<T>() where T : class
{
return (IBaseBusiness) Activator.CreateInstance(typeof(T));
}
}
Unit test:
I tried to stub the IBusinessFactory and inject into my class under test so I can fake the implementations that the class uses.
Example: failing to complete TestInit method, and it's failing when instantiating stub of class2.
interface IClass1 : IBaseBusiness{}
public Class1 : IClass1{}
interface IClass2 : IBaseBusiness{}
public Class2 : IClass2{}
public TestFactory{
[TestInitialize]
public void TestInit()
{
var fkBusFac = new StubIBusinessFactory();
fkBusFac.CreateOf1<Class1>(() => new StubIClass1() { });
fkBusFac.CreateOf1<Class2>(() => new StubIClass2() { });
}
Can anyone please help?
Not an answer to your question, but...
What happens if I do the following?:
var business = Create<string>();
You have absolutely no type safety at all here. If the created object implements IBaseBusiness, ensure it does and simply call new() (oh, and if its a factory method, shouldn't you be making it static?):
public static IBaseBusiness Create<T>() where T : IBaseBunsiness, new()
{
return new T();
}

How to create an interface that keeps some methods internal for testing in C#?

Consider the following class
public class Entity {
public void Foo() { ... }
internal void Bar() { ... }
}
As you see it has a public method and an internal method. Now, I would like to create an interface which will allow me to mock this class in tests (both in this assembly and in others). I rewrite my code as following:
public interface IEntity {
void Foo();
}
internal class Entity : IEntity {
public void Foo() { ... }
public void Bar() { ... }
}
However, this creates another issue. When using the class in another method in the same assembly I can't call Bar anymore:
public class OtherClass {
public void SomeMethod(IEntity entity) {
entity.Bar(); // error!
}
}
Rewriting the code like this:
public class OtherClass {
public void SomeMethod(IEntity entity) {
(entity as Entity).Bar(); // error in test!
}
}
will trigger an error in the unit test that triggers SomeMethod. How do I rewrite my code so that I can still use internal methods in the same assembly and yet only expose public members to other assemblies?
Update: Class OtherClass is a utility class that needs to operate on internals of the Entity class, which are not exposed to the users directly. However, this class itself is exposed to users, so they indirectly have access to internals of the Entity. This is desired as SomeMethod will perform necessary checks to ensure that users won't screw up the internal state of an Entity object.
How do I rewrite my code so that I can still use internal methods in the same assembly and yet only expose public members to other assemblies?
Make the interface internal and then explicitly implement it.
internal interface ITest
{
void Foo();
void Bar();
}
public class Thing : ITest
{
void ITest.Foo() { this.Foo(); }
void ITest.Bar() { this.Bar(); }
public Foo() { ... }
internal Bar() { ... }
}
So now public class Thing has only one public method Foo. Code outside the assembly cannot call Bar either directly or via a conversion to the interface because Bar and ITest are both internal.
I note that a base class must be at least as visible as its deriving class. Not so interfaces. Few people know that this is legal:
class C : C.I
{
private interface I {}
}
A class can implement an interface that only it can see! This is a bit of a strange thing to do but there are some situations where it makes sense.
Edited:
Extend your IEntity interface with an internal ITestEntity interface for testing:
public interface IEntity
{
//Implementation
}
internal interface ITestEntity : IEntity
{
void TestMethod();
}
class Entity: ITestEntity
{
//
}
I assume you want to call the internal method only in your unit tests right? Because otherwise, exposing the method to other assemblies would require to replace internal with public of cause.
For unit testing in general, it is always a good pattern if you DO NOT test private or internal methods. A Unit test should actually just test the public interface and any business class should provide public methods which do whatever internally...
So to test your internal methods, you would have to test the public representation of it.
But anyways. If you want to test private or internal accessor, Visual Studio Test projects usually can generate accessor wrappers for you.
You would have to call the accessor ctor instead of the normal ctor of your class. When you do so, you can access any private or internal methods/properties of that instance.
Find more information about those generated types here: http://msdn.microsoft.com/en-us/library/bb385974(v=vs.100).aspx
:edit: after discussion, I have an Example for you of how to use moq together with Unity and UnityAutoMoq (3 different Nugets).
Lets say your class looks like this:
public class MyClassWithInternalMethod
{
internal object GetSomething()
{
return null;
}
}
To test this you can mock it like this:
using (var moqUnityContainer = new UnityAutoMoqContainer())
{
moqUnityContainer.GetMock<MyClassWithInternalMethod>().Setup(p => p.GetSomething()).Returns(null);
}

How to create instance of inherited in static base method?

From an instance, I might do this.
var obj= Activator.CreateInstance(GetType());
Not sure how to get typeof of the inherited class in a static base method though.
Is this the best way forward?
public static Method<T>() where T : SomeBase, new()
You could make the base class generic and close the generic in the derived class.
public abstract class CreatorOf<T> where T : CreatorOf<T>
{
public static T Create()
{
return (T)Activator.CreateInstance(typeof(T));
}
}
public class Inheritor : CreatorOf<Inheritor>
{
public Inheritor()
{
}
}
public class Client
{
public Client()
{
var obj = Inheritor.Create();
}
}
There are some who consider this to be an "anti-pattern", but I believe there are circumstances where it is an acceptable approach.
Maybe you should better tryto use abstract factory pattern?
http://en.wikipedia.org/wiki/Abstract_factory_pattern
There is no such thing as a derived static method. So there is no way to create a static factory method that returns a different type depending on which derived class you call it on.
As Lonli-Lokli suggested, you should use the Abstract Factory design pattern.
public interface ISomething
{
void DoSomething();
}
public class SomeClass : ISomething
{
public virtual void DoSomething() { Console.WriteLine("SomeClass"); }
}
public class SomeDerivedClass : SomeClass
{
private int parameter;
public SomeDerivedClass(int parameter)
{
this.parameter = parameter;
}
public virtual void DoSomething()
{
Console.WriteLine("SomeDerivedClass - {0}", parameter);
base.DoSomething();
}
}
public interface IFactory
{
public ISomething Create();
}
public class SomeClassFactory : IFactory
{
public ISomething Create() { return new SomeClass(); }
}
public class SomeDerivedClassFactory : IFactory
{
public ISomething Create() { return new SomeDerivedClass(SomeParam); }
public int SomeParam { get; set; }
}
Pros of Abstract Factory vs static Factory methods:
It is much more flexible, allowing a new implementation of your factory logic (which can be as complicated as you want) for every implementor of the abstract factory. You could have more than one factory per class, if you wanted.
Since you aren't calling a static method, it is much easier to replace at runtime. This is quite useful for injecting mocks in unit tests.
The pros are huge. Abstract Factories are superior to static factory methods in every way, even if you could get static methods to work the way you want them to.
Cons of Abstract Factory vs static Factory methods:
Users of the abstract factory must have a factory instance to create your derived types.
You have to write a new abstract factory implementation for each derived class.
The cons are very marginal.
It is extremely easy for a user to instantiate a factory to create a single object:
MyClass myClass = new MyClassFactory().Create();
As for code duplication in the factory implementation: Saving the implementer a tiny bit of typing is pointless. It is a goal in programming to write code that can be read, understood, and easily modified. There is no programming goal to save paper or keystrokes :)

C# virtual (or abstract) static methods

Static inheritance works just like instance inheritance. Except you are not allowed to make static methods virtual or abstract.
class Program {
static void Main(string[] args) {
TestBase.TargetMethod();
TestChild.TargetMethod();
TestBase.Operation();
TestChild.Operation();
}
}
class TestBase {
public static void TargetMethod() {
Console.WriteLine("Base class");
}
public static void Operation() {
TargetMethod();
}
}
class TestChild : TestBase {
public static new void TargetMethod() {
Console.WriteLine("Child class");
}
}
This will output:
Base class
Child class
Base class
Base class
But I want:
Base class
Child class
Base class
Child class
If it I could on static methods, I would make TargetMethod virtual and it would do the job. But is there a work around to get the same effect?
Edit: Yes, I could put a copy of Operation in the child class, but this would require copy and pasting a large bit of code into every child, which in my case is about 35 classes, a maintenance nightmare.
No, you cannot override a static method. "static" also means that it is statically bound by the compiler, so the actual method to be called is not found at runtime, but bound at compile time.
What you should do is make the class non-static. Make the method virtual and override it and make full benefit of real inheritance. Then, if you really need it, make a static entry point to a reference of your class. For instance a static factory, singleton (it's an anti-pattern in most of the cases but is as good as a static class) or just a static property.
You could store the TargetMethod as a delegate, which a subclass could change as needed:
class TestBase {
protected static Action _targetMethod;
static new() {
_targetMethod = new Action(() => {
Console.WriteLine("Base class");
});
}
public static void TargetMethod() {
_targetMethod();
}
public static void Operation() {
TargetMethod();
}
}
class TestChild : TestBase {
static new() {
_targetMethod = new Action(() => {
Console.WriteLine("Child class");
});
}
}
Since these are static instances, though - the _targetMethod is shared across all instances - changing it in TestChild changes it for TestBase as well. You may or may not care about that. If you do, generics or a Dictionary<Type, Action> might help.
Overall, though, you'd have a much easier time if you didn't insist on statics, or perhaps used composition instead of inheritance.
If you are looking to do abstract static methods, then this works, and turns out to be the easiest solution for me to adapt to:
class TestBase<ChildType> where ChildType : TestBase<ChildType> {
//public static abstract void TargetMethod();
public static void Operation() {
typeof(ChildType).GetMethod("TargetMethod").Invoke(null, null);
}
}
class TestChild : TestBase<TestChild> {
public static void TargetMethod() {
Console.WriteLine("Child class");
}
}
But I am still marking Stafan as the solution because using instance inheritance is probably the best recommendation for anyone in a similar situation. But I simply would have to rewrite too much code for it.
Ok here is what I have done
public abstract class Base<T>
where T : Base<T>, new()
{
#region Singleton Instance
//This is to mimic static implementation of non instance specific methods
private static object lockobj = new Object();
private static T _Instance;
public static T Instance
{
get
{
if (_Instance == null)
{
lock (lockobj)
{
if (_Instance == null)
{
_Instance = new T();
}
}
}
return _Instance;
}
}
#endregion //Singleton Instance
#region Abstract Definitions
public abstract T GetByID(long id);
public abstract T Fill(SqlDataReader sr);
#endregion //Abstract Definitions
}
public class InstanceClass : Base<InstanceClass>
{
//empty constructor to ensure you just get the method definitions without any
//additional code executing
public InstanceClass() { }
#region Base Methods
public override InstanceClass GetByID(long id)
{
SqlDataReader sr = DA.GetData("select * from table");
return InstanceClass.Instance.Fill(sr);
}
internal override InstanceClass Fill(SqlDataReader sr)
{
InstanceClass returnVal = new InstanceClass();
returnVal.property = sr["column1"];
return returnVal;
}
}
I think this will be a viable solution for what you want to do without breaking too many purist OO principles.

Categories

Resources