Is there a built in interface that implements Convert.ToInt64()?
I'm trying to mock a class that is responsible for converting a string to a long, but I don't know which interface to use. It doesn't have to be Convert.
I can't imaging I'm the only one who needs a testable class that converts strings to longs.
To help with mocking, do not call Convert.ToInt64() directly. Instead, create a simple wrapper interface and use dependency injection:
public interface IStringToLong {
long StringToLong(string val);
}
public class StringToLong : IStringToLong {
public long StringToLong(string val) => Convert.ToInt64(val);
}
// While using dependency injection
public class SomeClass {
private readonly IStringToLong _stringToLong;
public SomeClass(IStringToLong stringToLong) {
_stringToLong = stringToLong;
}
public void SomeMethod {
// Instead of Convert.ToInt64("10000"), use this:
var someLong = _stringToLong.StringToLong("10000");
}
}
Now when testing SomeClass you can use a mocked object created from the IStringToLong interface.
Convert is a static class, so it cannot have an interface. I'm not sure what you are trying to do without looking at some code, but if you truly need to mock Convert.ToInt64, you could use Func<string, long>, then in your tests pass a mock function, i.e. anyString => 21122.
Related
Given an interface like:
public interface IFoo
{
string Bar();
}
And a class that implements it like:
public class Foo : IFoo
{
public string Bar()
{
returns "Bar";
}
public string SomeOtherMethod()
{
returns "Something else";
}
}
Is there a problem with this code? Should we add all methods to the interface?
One example: imagine a private method that grows complex enough to need unit tests. Could you make it public (so it can be called from the test project) but not add it to the interface (because no clients need to call it)?
If what a class does is simple enough that we can test its public methods and private methods at the same time, then we can just test the public methods.
If the private method grows so complex that between the public and private method we need too many combinations of tests then it's time to separate the private method into its own class. Making the private method public would break the encapsulation of the class. Even if we don't add the method to an interface, making the class method public still adds the method to the public interface of the class itself.
So if we have this:
public class ClassWithComplexPrivateMethod
{
public void DoSomething(int value)
{
PrivateMethodThatNeedsItsOwnTests(value);
}
private string PrivateMethodThatNeedsItsOwnTests(int value)
{
// This method has gotten really complicated!
return value.ToString();
}
}
We might refactor to something like this:
public interface IRepresentsWhatThePrivateMethodDid
{
string MethodThatNeedsItsOwnTests(int value);
}
public class RefactoredClass
{
private readonly IRepresentsWhatThePrivateMethodDid _dependency;
public RefactoredClass(IRepresentsWhatThePrivateMethodDid dependency)
{
_dependency = dependency;
}
public string DoSomething(int value)
{
return _dependency.MethodThatNeedsItsOwnTests(value);
}
}
And now a new class implements IRepresentsWhatThePrivateMethodDid.
Now when we test the refactored class we mock IRepresentsWhatThePrivateMethodDid, and we write separate unit tests for any classes that implement IRepresentsWhatThePrivateMethodDid.
It may seem like a contradiction to say that exposing the private method as public breaks encapsulation, but exposing it as its own separate class doesn't. There are two differences:
The refactored class doesn't depend on the new class containing what used to be the private method. It depends on the new interface.
The interaction between the refactored class and the interface is still hidden within its methods. Other classes that call its public methods don't "know" about how it uses its dependency. (In fact, other classes will likely depend on abstractions instead of directly on the refactored class.)
It's also easy to get carried away with this and introduce the separate dependency too soon, when we could have tested the class - including its private methods - through the public methods. I've done this lots of times, and it can result in lots and lots of unnecessary interfaces and extra classes. There's no perfection, just our best efforts to balance it.
One more thought: We tend to use interfaces to represent dependencies, but we don't have to. If what we're extracting was just a single private method, then perhaps we can represent it with a delegate or a Func instead, like this:
public class RefactoredClass
{
private readonly Func<int, string> _dependency;
public RefactoredClass(Func<int, string> dependency)
{
_dependency = dependency;
}
public string DoSomething(int value)
{
return _dependency(value);
}
}
Or we can use a delegate, which I like better than Func because it indicates what the function does.
Generally when a class implements an interface all members of an interface must be implemented, it does not go the other way around.
Also when implementing an interface member, the corresponding member of the implementing class must be public, non-static, and have the same name and parameter signature as the interface member. You can have methods, even public, in the class that are not defined in the interface.
On top of that, the interface itself provides no functionality that a class or struct can inherit in the way that it can inherit base class functionality. However, if a base class implements an interface, any class that's derived from the base class inherits that implementation.
Interface should represent just the required API without regard to unit-testing and smth else.
To test public-methods of class you should do nothing because Test-project has access to them. You just need to instantiate a class and inject all required dependency using Mock.
Example: testing class without any dependencies
Example: testing class with dependency
To test private methods of a class need to make them visible to test-project:
mark private methods as internal
make internal-method visible to test-project: add to AssemblyInfo.cs the directive [assembly: InternalsVisibleTo("Project.Tests")] (see InternalsVisibleToAttribute)
Recently, I saw this code. Since I am trying to learn few things at once, I am having issues with this code but dont know how to resolve. I would like to be able to unit test this code
public static class CarFactory
{
private static readonly IDictionary<string, Type> CarsRegistry = new Dictionary<string, Type>();
public static void Register<TCar>(string car) where TCar : CarBase, new()
{
if (!CarsRegistry.ContainsKey(car))
{
CarsRegistry.Add(car, typeof(TCar));
}
}
public static ICar Create(string car)
{
if (CarsRegistry.ContainsKey(car))
{
CarBase newCar = (CarBase)Activator.CreateInstance(CarsRegistry[car]);
return newCar;
}
throw new NotSupportedException($"Unknown '{car}'");
}
}
I have few problems with this code.
Name is CarFactory but this does not look like a Factory Pattern to me. It looks more like Locator Pattern
The class is static - and I heard static classes are bad for unit testing in frameworks like Moq and that they also hide dependencies. Say a method in another regular class uses this, for unit test, there is no way to know that that method depend on this static class
I would like to ensure this class is called properly and I think based on my reading that this is Locator Pattern.
I would also like to unit test this class and need help to make it unit testable using Moq.
Thanks to #ErikPhillips explanation below, I now understand that other classes using this class will be not testable. So, if I have a class like below:
public class CarConsumer
{
public void ICar GetRedCar()
{
var result = CarFactory.Create("Tesla");
result.Color = Color.Red;
return result;
}
}
, GetRedCar() method will be difficult to test because it uses CarFactory static class and for a unit test or an outside client, there is nothing in GetRedCar() method API that suggest it is depending on this static class.
I would like to refactor CarFactory class so other classes using it like in example above CarConsumer class can be tested properly.
I would like to be able to unit test this code
What specific problems prevent you from unit testing this class? It has two methods, seems pretty straight forward to write a unit test against.
Name is CarFactory but this does not look like a Factory Pattern to me
I believe a Factory Pattern is
The factory method pattern is a creational pattern that uses factory methods to deal with the problem of creating objects without having to specify the exact class of the object that will be created
I pass in the name of the car (so I haven't specified the type) and it creates the class for me. That's pretty much it. Is it a good example of one? Not in my opinion, but my opinion of how well it's done doesn't change what it is.
This doesn't mean it's not Service Locator, but it definitely is a Factory Method.
(Honestly it doesn't look like a service locator because it only delivers a single service)
unit testing in frameworks like Moq
Moq is not a Unit-Testing framework. Moq is a Mocking Framework. Static classes are not easy to Mock. If you can Mock it, you can unit-test with methods that require a mocked class.
static classes .. that they also hide dependencies.
Any poorly designed anything can do anything. Static Classes aren't by definition designed to hide anything.
I would say in this instance, that this Static Class, prevents you from being able to Mock it easily to unit test other methods that rely on the Static Classes methods.
I would also like to unit test this class and need help to make it unit testable using Moq.
Again, there is nothing preventing you from unit-testing this class.
public class CarFactoryTests
{
public class MoqCar : CarBase { }
public void Register_WithValidParameters_DoesNotThrowException
{
// Act
Assert.DoesNotThrow(() => CarFactory.Register<MoqCar>(
nameof(Register_WithValidParameters_DoesNotThrowException)));
}
public void Create_WithValidCar_DoesNotThrowException
{
CarFactory.Register<MoqCar>(
nameof(Create_WithValidParameters_DoesNotThrowException));
Assert.DoesNotThrow(() => CarFactory.Create(
nameof(Create_WithValidParameters_DoesNotThrowException));
}
// etc etc
}
The problem you may run into is
public class CarConsumer
{
public void ICar GetRedCar()
{
var result = CarFactory.Create("Tesla");
result.Color = Color.Red;
return result;
}
}
Testing this method means that you are not in full control of the method because there is external code GetRedCar() relies on. You cannot write a pure unit test here.
This is why you'd have to convert CarFactory to an instance class. And then make sure it's has the correct lifetime for whatever DI framework you're using.
public class CarConsumer
{
private ICarFactory _carFactory;
public CarConsumer(ICarFactory carFactory)
{
_carFactory = carFactory;
}
public void ICar GetRedCar()
{
var result = _carFactory.Create("Tesla");
result.Color = Color.Red;
return result;
}
}
Now we can Moq ICarfactory and write pure unit test against GetRedCar().
The following is not recommended.
If for whatever reason you are stuck with this type of Factory but you still want to write pure unit tests, you can do something like:
public class CarConsumer
{
private Func<string, ICar> _createCar;
public CarConsumer(Func<string, ICar> createCar= CarFactory.Create)
{
_createCar = createCar;
}
public void ICar GetRedCar()
{
var result = _createCar("Tesla");
result.Color = Color.Red;
return result;
}
}
We can Moq this type of Func, but it's really just a crutch for the real problem.
I guess the real question I have is how to make my CarFactory so that methods from other classes using it can be tested using Moq?
public interface ICarFactory
{
void Register<TCar>(string car) where TCar : CarBase, new();
ICar Create(string car);
}
public class CarFactory : ICarFactory
{
private readonly IDictionary<string, Type> CarsRegistry
= new Dictionary<string, Type>();
public void Register<TCar>(string car) where TCar : CarBase, new()
{
if (!CarsRegistry.ContainsKey(car))
{
CarsRegistry.Add(car, typeof(TCar));
}
}
public ICar Create(string car)
{
if (CarsRegistry.ContainsKey(car))
{
CarBase newCar = (CarBase)Activator.CreateInstance(CarsRegistry[car]);
return newCar;
}
throw new NotSupportedException($"Unknown '{car}'");
}
}
I have an abstract factory like this.
public abstract class AbstractFactory
{
public abstract ISyncService GetSyncService(EntityType entityType);
}
And I have its concrete implementation like this.
public class SyncFactory : AbstractFactory
{
private readonly IOperatorRepository _operatorRepository;
public SyncFactory( IOperatorRepository operatorRepository)
{
_operatorRepository = operatorRepository;
}
public override ISyncService GetSyncService(EntityType entityType)
{
return new OperatorSyncService(_operatorRepository);
}
}
This concrete factory is accessed in a method like this.
public void MethodTobeTested()
{
var syncService =
new SyncFactory(_operatorRepository).GetSyncService(entityType);
}
Now I need to write a unit test for MethodTobeTested().
I mocked the return value of the GetSyncService() like this. But it's calling the actual OperatorSyncService, not the mock. I need this mock to mock another method inside OperatorSyncService
private Mock<SyncFactory> _syncServiceMock;
_syncServiceMock = new Mock<SyncFactory>();
_syncServiceMock.Setup(m => m.GetSyncService(operator)).Returns(_operatorSyncServiceMock.Object);
Any idea on how to resolve this?
In your SyncFactory implementation you inject an instance of IOperatorRepository. This is great because it allows you to inject a different version if needs be and creates a seem for you to use a mock implementation of IOperatorRepository.
You have also made an abstract factory which looks good but it looks like the problem is with your usage of the factory;
var syncService =
new SyncFactory(_operatorRepository).GetSyncService(entityType);
In your MethodToBeTested you create a concrete implementation of SyncFactory, this make the point of the abstract factory a little redundent since you cannot inject a different implementation. I don't know where you are geting your _operatorRepository instance from but I can see two ways forward.
In the constructor of the class that contains MethodToBeTested add a parameter that takes an instance of your abstract factory, then get your MethodToBeTested to use this injected factory instead of creating a new one, this would allow you to mock the whole factory - this is my recommended approach because the class containing MethodToBeTested would no longer need to know how to create a factory instance which it shouldn't if you are following the single responsibility principle. There would be no dependence on any concrete implementation.
As above but instead inject IOperatorRepository rather than the factory, you can then inject a mock IOperatorRepository but I would advise against this since you've done such a good job of creating all your abstractions to then cast this work aside and "new up" an instance of syncFactory and creating a concrete dependency
MethodToBeTested is tightly coupled to SyncFactory because the method is manually creating a new instance of SyncFactory. This makes mocking the dependency very difficult.
Assuming
public class ClassToBeTested {
public void MethodTobeTested() {
var syncService = new SyncFactory(_operatorRepository).GetSyncService(entityType);
//...other code
}
}
ClassToBeTested should be refactored to
public class ClassToBeTested {
private readonly AbstractFactory syncFactory;
public ClassToBeTested (AbstractFactory factory) {
this.syncFactory = factory
}
public void MethodTobeTested() {
var syncService = syncFactory.GetSyncService(entityType);
//...other code
}
}
This will allow the dependency to be mocked and injected into the class to be tested and accessed by the method to be tested. The class to be tested now only needs to know what it needs to know. It now no longer needs to be aware of IOperatorRepository.
The new in the method MethodTobeTested creates new instance so no mock can be injected. Inject the factory e.g. as parameter so it can be mocked in the test.
public void MethodTobeTested(AbstractFactory factory)
{
EntityType entityType = null;
var syncService = factory.GetSyncService(entityType);
}
[TestMethod]
public void Method_Condition_Result()
{
// Arrange
TestedClass tested = new TestedClass();
Mock<ISyncService> syncServiceMock = new Mock<ISyncService>();
Mock<AbstractFactory> factoryMock = new Mock<AbstractFactory>();
factoryMock.Setup(f => f.GetSyncService(It.IsAny<EntityType>())).Returns(syncServiceMock.Object);
// Act
tested.MethodTobeTested(factoryMock.Object);
// Assert
// ...
}
This is how I want to use it:
var fooStuff = _foo.DoBarStuff().GetFooStuff(id);
I'd like to return the implementation when DoBarStuff() is called so that I can call GetFooStuff(id) to get fooStuff.
public interface IFoo() : IBar
{
FooStuff GetFooStuff(int id);
}
public class Foo
{
public FooStuff GetFooStuff(int id)
{
// get fooStuff
return fooStuff;
}
}
public interface IBar
{
T DoBarStuff<T>();
}
public class Bar
{
public T DoBarStuff<T>()
{
// do bar stuff
return T;
}
}
The T is any interface and when 'return T;' is executed I need it's implementation returned. As it is now, I get this error under T on 'return T;' line.
T is a type, which is not valid in the given context. Type parameter
name is not valid at this point.
Thanks!
This should work:
public interface IBar
{
T DoBarStuff<T>() where T : class, new();
}
public class Bar : IBar
{
public T DoBarStuff<T>() where T : class, new()
{
// do bar stuff
return new T();
}
}
But you will have to specify the type when using the method DoBarStuff:
Usage: var fooStuff = _foo.DoBarStuff<FooWhatEver>().GetFooStuff(id)
If you don't want to, make your class/interface generics:
public interface IBar<T> where T : class, new()
{
T DoBarStuff<T>();
}
public class Bar<T> : IBar<T> where T : class, new()
{
public T DoBarStuff()
{
// do bar stuff
return new T();
}
}
Usage:
IBar bar = new Bar<FooWhatEver>();
var fooStuff = _foo.DoBarStuff().GetFooStuff(id);
But all of this doesn't work for interface, only instantiable classes (with a default constructor).
For interfaces, you will need something to make the conversion between them and theirs implementations.
The simple way is to use a dictionary (for the testing purpose, but you can use dependency injection framework as #N_tro_P suggested, even if choosing between one of them, now, shouldn't be your main goal).
You will end up with something like this (don't forget your inheritance and the generic part):
public class Bar // <T> or not depending on your choice
// You can add this constraint to avoid value types (as int):
// where T : class
{
Dictionary<Type, Type> _container = new Dictionary<Type, Type>();
{
{typeof(IFoo), typeof(Foo)}
};
public T DoBarStuff() // <T> or not depending on your choice
// You can add this constraint to avoid value types (as int):
// where T : class
{
// get fooStuff
return Activator.CreateInstance(_container[typeof(T)]);
// You will get an error if T is not in the container
// or if _container[typeof(T)] is not instantiable
// or doesn't have a default constructor.
}
}
The only problem is, you will have to fill the dictionary/container with all your interfaces/classes you want to use, it can become pretty annoying to deal with.
You might want prefer to use one of my first solutions instead.
You can do this but not how you wrote your calling signature.
You never had your Bar not use IBar and Foo use it as an interface. So you should change that. You may be confusing how to interact with interfaces.
Adjusted Code
public interface IFoo
{
FooStuff GetFooStuff(int id);
}
public class Foo : IFoo
{
public FooStuff GetFooStuff(int id)
{
// get fooStuff
return fooStuff;
}
}
public interface IBar
{
T DoBarStuff<T>();
}
public class Bar : IBar
{
public T DoBarStuff<T>()
{
// do bar stuff
return container[typeof(T)];
}
}
The usage of what you are asking is to ensure you put the type in then, such as this.
var fooStuff = _foo.DoBarStuff<BarStuff>().GetFooStuff(id);
This is how dependency containers work. They store with in it a Dictionary an instantiated object using the type as a key. i.e.
Dictionary instances;
Then you can also have factories stored elsewhere, but that requires your signitures match or you just assume they have independent access to their dependencies, so you would have
Dictionary> factories;
In general though, I would take a look at dependency containers. Whatever you are working on may simply be calling for it as a pattern and there are many already made so no need to roll your own. If you are wanting to return objects by type, that is a dependency container.
Also, I would recommend injecting that through so you are not coupled to an container. In other words, wrap it in an interface and then use an off the shelf one (Unity, MEF, etc.)
public interface IDependencyContainer
{
T Resolve<T>();
void Register<T>(T instance);
void Register<T>(Func<T> instance);
}
I have a class similar to the following:
public abstract class Manager<T, TInterface> : IManager<T> where TInterface : IRepository<T>
{
protected abstract TInterface Repository { get; }
public virtual List<T> GetAll()
{
return Repository.GetAll();
}
}
This works perfectly fine, however, is there a way to get away from having the TInterface in the abstract class declaration and in the resulting class that extends my generic abstract class:
public class TestManager : Manager<TestObject, ITestRepository>, ITestManager
I am forced to use ITestRepository and make the Repository property abstract due to the fact that it can contain custom methods that I need to know about and be able to call.
As I continue to build layers, I will have to keep doing this process the whole way up the stack. Examples would be if I had a generic abstract controller or service layer:
public class TestService : Service<TestObject, ITestManager>, ITestService
Is there a better way to do this or is this the best practice to allow a generic class to call another generic class?
It seems that all you want to do is to make Manager<T> testable, and use a mock as a repository that you can query for special members.
If that's the case, maybe you can change your design to this:
public class Manager<T> : IManager<T> {
protected IRepository<T> Repository { get; set; }
// ...
public virtual List<T> GetAll() {
return Repository.GetAll();
}
}
Now, all the specifics of testing are in a testing subclass:
public class TestingManager<T> : Manager<T> {
public new ITestRepository<T> Repository {
get {
return (ITestRepository<T>)base.Repository;
}
set {
base.Repository = value;
}
}
}
When you write your unit tests, you create TestingManager<T> instances (referenced through TestingManager<T> declared variables and fields), and you provide them with a test repository. Whenever you query their Repository, you'll always get a strongly-typed test repository.
UPDATE:
There's another way to solve this, without a subclass. You declare your repository objects as test repositories that you pass to Manager<T>s and you query them directly, without going through the Manager<T>.
[Test]
public void GetAll_Should_Call_GetAll_On_Repository_Test() {
var testRepository = new TestRepository();
var orderManager = new Manager<Order>(testRepository);
// test an orderManager method
orderManager.GetAll();
// use testRepository to verify (sense) that the orderManager method worked
Assert.IsTrue(testRepository.GetAllCalled);
}
No, you can't get around it. You can try, but the result will be ugly and in some way incorrect. The reason is that you are asking generics not to be generic but still be generic.
If a new class uses a generic class, either in inheritance or composition, and it itself does not know enough to specify the type parameters to the generic class it is using, then it must itself be generic. It is analogous the method call chains, where a method may pass parameters along to another method. It can't make up the arguments to the inner method, but must rather take them as parameters itself from a caller that does know what they are. Type parameters are the same.
One thing that does make this feel like code smell is the fact that you can't have a variable of type Manager<,>. It has to be fully type-specified. One solution I've come up with is to have non-generic interfaces that the generic classes implement. These interfaces have as much of the public interface of the generic class as is possible (they can't have methods or properties that reference the type parameters). Then you can pass around variables of the type of the interface and not have to specify type parameters.
Example:
interface IExample {
string Name { get; }
void SomeNonGenericMethod(int i);
}
class Example<T> : IExample {
public string Name { get { ... } }
public void SomeNonGenericMethod(int i) {
...
}
public T SomeGenericMethod() {
...
}
}