C# Multiple Stub implementation for method with T - c#

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();
}

Related

Are there any rules for type conversion between C# generics?

I'm having an interface IJob from which all Job classes inherits and I have generic repo class which will process all kind of IJob's.
The problem im facing is im not able to able convert Repository<Job1> to Repository<IJob> even though Job1 is a type of IJob.
Code
internal class Program
{
public interface IJob { }
public class Job1 : IJob { }
public class Job2 : IJob { }
public class Repository<TJob>
where TJob : IJob
{
public List<TJob> GetJobs()
{
return new List<TJob>();
}
}
private static void Main(string[] args)
{
IJob iJob = new Job1(); // Valid
Repository<IJob> repo = new Repository<Job1>(); // Not Valid
}
}
Can someone let me know why this wont be possible in C# and are there any other rules type conversion in C# generics?
If you want covariance, then you'll have to introduce a generic interface for the repository and change the return type of the GetJobs method to IEnumerable<TJob>:
internal class Program
{
public interface IJob { }
public class Job1 : IJob { }
public class Job2 : IJob { }
public interface IRepository<out TJob> where TJob : IJob
{
IEnumerable<TJob> GetJobs();
}
public class Repository<TJob> : IRepository<TJob> where TJob : IJob
{
public IEnumerable<TJob> GetJobs()
{
return new List<TJob>();
}
}
private static void Main(string[] args)
{
IJob iJob = new Job1(); // Valid
IRepository<IJob> repo = new Repository<Job1>(); // Also valid
}
}
For more information about covariance and contravariance, see: https://msdn.microsoft.com/en-us/library/dd799517%28v=vs.110%29.aspx
Repository<IJob> repo = new Repository<Job1>(); // Not Valid
Yes, because it isn't an Repository<IJob>. With an Repository<IJob>, this line would be valid:
repo.GetJobs().Add(new Job2());
Now, with a Repository<Job1>, this line is invalid. It won't compile.
So the error you get is correct. A Repository<Job1> is not a Repository<IJob>.
You simply want
Repository<IJob> repo = new Repository<IJob>();
then you can add any IJob to the repository.
repo.Add(new Job1());
repo.Add(new Job2());
to understand why it cannot be done we need to go back what means to be a subclass of an object in c#. when you have a situation like this:
public class A
{
public A GetInstance { get;set;}
}
public class B : A
{
}
class B inherits all methods from class A including the signature of the method. in fact, you can create an instance of B that has a GetInstance method ThatReturns A, but not B. if you try to override the GetInstance method to return B, it will of course give a compilation error (a method cannot be ovveridden if the only change is the return type).
using a generics is a bit different because changing the type in input will change the signature of all the methods.
Simply put, even if Job1 is a subclass of IJob, methods of class Repository(IJob) have a different signature of methods of class Repository(Job1) so they are not related, but like two separate classes.

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);
}

NUnit - Static Vs. Public methods

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.

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 :)

Autofac - resolving component with parameters dynamically

I have a class that takes an interface as a constructor argument. There are two implementations of this interface and I want to decide what implementation to use at runtime based on a variable.
The problem is that the class above is deep in an object heirarchy that is resolved by Autofac and so I can't pass in the argument.
Somehing like below is what I am trying to achieve.
public interface IInterface1 {}
public interface IInterface2 {}
public class Class1 : IInterface2
{
public Class1(IInterface1 interface1)
{
}
}
public class Class2
{
public Class2(IInterface2 interface2)
{
}
}
public class Class3
{
public void GetClass2Instance(string interface1ImplementationToChoose)
{
// want to change which implementation of IInterface1 is resolved based on the interface1ImplementationToChoose variable
var class2 = container.Resolve<Class2>();
}
}
Any ideas?
UPDATE:
To clarify, this is an existing object hierarchy that is used by existing applications that work fine. Also, the object model is much larger than the one shown in this example. As a result I don't really want to have to pass down a factory to each constructor in the object graph to be used by a class deep in that graph.
Is there a way of getting a different implementation of IInterface1 passed into Class1 without Class2 knowing anything about it?
Thanks
Yes, inject a factory that hides how the types are chosen:
public class Class3
{
private Func<string, Class2> _class2Factory;
public Class3(Func<string, Class2> class2Factory)
{
_class2Factory = class2Factory;
}
public void GetClass2Instance(string interface1ImplementationToChoose)
{
var class2 = _class2Factory(interface1ImplementationToChoose);
}
}
And then the container setup, something along these lines:
builder.RegisterType<Implementation1>().Named("imp1").As<IInterface1>();
builder.RegisterType<Implementation2>().Named("imp2").As<IInterface1>();
builder.Register<Func<string, Class2>>(c =>
{
var context = c.Resolve<IComponentContext>();
return imp => new Class2(context.Resolve<IInterface1>(imp));
});
builder.RegisterType<Class3>();
You can now use Class3 like this:
public class Class4
{
public Class4(Class3 class3)
{
var class2with1 = class3.GetClass2Instance("imp1");
var class2with2 = class3.GetClass2Instance("imp2");
}
}
NOTE: I have assumed that you meant that Class2 should be injected with varying implementations of the same interface IInterface1. Your sample is a bit confusing since you are showing two classes that implements different interfaces.

Categories

Resources