This is a dilemma. Say we have two classes
Class A
{
public int memberValue;
}
interface IB
{
int fun();
}
Class B : IB
{
public int fun()
{
var a = new A();
switch(a.memberValue)
{
case 1:
//do something
break;
case 2:
//do something
break;
}
}
}
Now this presents two tightly coupled classes.
For testing B.fun(), we need to mock Class A and provide multiple values for A.memberValue.
As the A object is not required anywhere else beyond the scope of B.fun(), I dont see why should we inject it through B's constructor.
How can we unit test this method fun() ?
Firstly you should probably create an interface for A as well, but if this is just a simple POCO data class, it might be better to just make its properties virtual instead to allow for mocking. You have 3 options I think:
Inject A to the constructor of B if it is a class that will be used often (e.g. a logging class or something). Then you can create a mock version in your test to check how A is used (remember, mocking is for testing behaviour with dependencies).
public class A : IA { ... }
public class B : IB
{
private readonly A a;
public B(IA a)
{
this.a = a;
}
public void Func()
{
//... use this.a ...
}
}
[Test]
public void Func_AHasValue1_DoesAction1()
{
Mock<IA> mock = new Mock<IA>();
mock.Setup(a => a.somevalue).Returns("something");
B sut = new B(mock.Object);
sut.Func();
mock.Verify(m => m.SomethingHappenedToMe());
}
Pass A to the method if it is something that B needs to work with (as it seems here). You can still create a mock version for use in your tests. This is the same code as the above, but mock is passed to the method instead of the constructor. This is the better method if A is some data class generated at runtime instead of a class with behaviour.
Create a factory class for A and inject that into the constructor. Change the method to get A instances from the factory and inject a mock factory in your tests to verify the behaviour.
public class AFactory : IAFactory
{
public IA Create() { ... }
}
public class B : IB
{
private readonly IAfactory factory;
public B(IAFactory factory)
{
this.factory = factory;
}
public void Func()
{
IA a = factory.Create();
//... use this.a ...
}
}
[Test]
public void Func_AHasValue1_DoesAction1()
{
Mock<IAFactory> mockFactory = new Mock<IAFactory>();
Mock<IA> mock = new Mock<IA>();
mockFactory.Setup(f => f.Create()).Returns(mock.Object);
mock.Setup(a => a.somevalue).Returns("something");
B sut = new B(mockFactory.Object);
sut.Func();
mock.Verify(m => m.SomethingHappenedToMe());
}
Option 1 is the standard approach for classes that can be built without any runtime information (e.g. logging classes).
Option 2 is better for when the input is only a data class that is generated at runtime (e.g. a user fills in a form and you have a POCO data class representing the form input).
Option 3 is better when A is something that does have behaviour but can't be created without something generated at runtime.
You'll have to look at your application to see which is most applicable.
Well, you can do it in few ways. Easiest will probably be to create factory method and in tests create class that inherits B and overrides factory method. I think that's something Feathers or Gojko Adzic (I don't really remember in whose book I've read it, i suppose it was Feathers' Working Effectively with Legacy Code) propose in such situations. Sample implementation would be something like:
class B : IB
{
public int fun()
{
A a = this.CreateA();
...
}
protected A CreateA() { return new A(); }
}
and in unit test:
class BTest : B
{
protected override A CreateA() { return mockA(); }
}
This is pretty simple and straightforward solution that does not limit coupling at class level but at least moves different functionalities to different methods so method that does something does not care about object creation.
But you need to carefully think whether it is really what you want. For small, short project it may be fine. For something bigger or long term it may be useful to still refactor code and remove dependency on A from B to make classes less coupled. Also, the pattern you've shown starts to look like Strategy design pattern. Maybe you should not inject A but strategy object that will know how to handle your current situation? That's always thing that comes to my mind when I see if ladder or switch statement.
But it all depends on context and size of your project.
Related
I have a class T and a factory TFactory that creates objects of type T.
I want to make sure that only the factory is allowed to create new T objects.
A halfhearted solution would be to require the factory as a parameter in T's constructor, for the only purpose that only somebody who at least brings a factory object can create T's:
class T
{
public T(TFactory Tf)
{
if (!(Tf is TFactory))
throw new InvalidOperationException("No factory provided");
}
}
But wherever a TFactory is at hand, one could construct T's.
Another approach would be to check via stack tracing, if the constructor call really came from within a TFactory, but this seems overkill to me.
A third apporach would be to put both T and TFactory in an assembly of their own, ad make T's constructor internal. But a new project and assembly just for this purpose?
Any better idea anybody?
(Although my code is C#, this is probably a more general question)
Here's something very similar to your third approach: declare the factory as a inner class of T, and make T's constructor private:
public class T {
public class Factory {
public T GetT() {
return new T(); // simple implementation just for an example here
}
}
private T() {}
}
Since Factory is inside T, it can access the private constructor, but outside code cannot. If you don't want to create a separate assembly, you could consider this approach.
Note that you could still put the factory class and T in two different files, with partial classes:
public partial class T {
private T() {}
// other stuff about T here...
}
// in another file
public partial class T {
public class Factory {
public T GetT() {
return new T();
}
// other stuff about Factory here...
}
}
public abstract class T { }
public class TFactory
{
public T CreateT() => new TImpl();
private class TImpl : T { }
}
The second approach is the worst one. That behavior is absolutely unobvious and unclear to a client. Stack tracing also slows down execution. The 1st and the 2nd make sense.
If you want to have total control of instance creation put it into the type. Use a factory method. Remember, one should be reasonable when putting constraint on instance creation. E.g. the instance should be initiated with a polymorphal (virtual) method. One can't call such a method from a constructor (a very bad practice), so the method should be called after construction. For not to put that responsibility on the client, hide the constructor from one and provide a factory method.
abstract class Base
{
protected abstract void Initialize();
}
class Derived : Base
{
protected Derived() { /* ... */}
protected override void Initialize() { /* ... */}
public Derived CreateDerived()
{
var derived = new Derived();
derived.Initialize();
return derived;
}
}
I have a base class:
public abstract class MyBaseClass
{
protected virtual void Method1()
{
}
}
and a derived class:
public class MyDerivedClass : MyBaseClass
{
public void Method2()
{
base.Method1();
}
}
I want to write a unit test for Method2 to verify that it calls Method1 on the base class. I'm using Moq as my mocking library. Is this possible?
I came across a related SO link:
Mocking a base class method call with Moq
in which the 2nd answer suggests it can be achieved by setting CallBase property to true on the mock object. However it's not clear how this would enable the call to the base class method (Method1 in the above example) to be verified.
Appreciate any assistance with this.
Unit tests should verify behavior, not implementation. There are several reasons for this:
The results are the goal, not how you get the results
Testing results allows you to improve the implementation without re-writing your tests
Implementations are harder to mock
You might be able to put in hooks or create mocks that verify that the base method was called, but do you really care how the answer was achieved, or do you care that the answer is right?
If the particular implementation you require has side effects that you can verify, then that is what you should be validating.
Mocking the base class from the perspective of the derived class is not possible. In your simple example, I would suggest one of the two options.
Option 1: In the event that MyDerivedClass really shouldn't care what MyBaseClass is up to, then use dependency injection! Yay abstraction!
public class MyClass
{
private readonly IUsedToBeBaseClass myDependency;
public MyClass(IUsedToBeBaseClass myDependency){
_myDependency = myDependency;
}
public void Method2()
{
_myDependency.Method1();
}
}
Elsewhere in test land...
[TestClass]
public class TestMyDependency {
[TestMethod]
public void TestThatMyDependencyIsCalled() {
var dependency = new Mock<IUsedToBeBaseClass>();
var unitUnderTest = new MyClass(dependency.Object);
var unitUnderTest.Method2();
dependency.Verify(x => x.Method1(), Times.Once);
}
}
Option 2: In the event that MyDerivedClass NEEDS to know what MyBaseClass is doing, then test that MyBaseClass is doing the right thing.
In alternative test land...
[TestClass]
public class TestMyDependency {
[TestMethod]
public void TestThatMyDependencyIsCalled() {
var unitUnderTest = new MyDerivedClass();
var unitUnderTest.Method2();
/* verify base class behavior #1 inside Method1() */
/* verify base class behavior #2 inside Method1() */
/* ... */
}
}
What you're describing is not a test of your code, but a test of the behavior of the language. That's fine, because it's a good way to ensure that the language behaves the way we think it does. I used to write lots of little console apps when I was learning. I wish I'd known about unit testing then because it's a better way to go about it.
But once you've tested it and confirmed that the language behaves the way you expect, I wouldn't keep writing tests for that. You can just test the behavior of your code.
Here's a real simple example:
public class TheBaseClass
{
public readonly List<string> Output = new List<string>();
public virtual void WriteToOutput()
{
Output.Add("TheBaseClass");
}
}
public class TheDerivedClass : TheBaseClass
{
public override void WriteToOutput()
{
Output.Add("TheDerivedClass");
base.WriteToOutput();
}
}
Unit test
[TestMethod]
public void EnsureDerivedClassCallsBaseClass()
{
var testSubject = new TheDerivedClass();
testSubject.WriteToOutput();
Assert.IsTrue(testSubject.Output.Contains("TheBaseClass"));
}
I have a factory object ChallengeManager to generate instances of a Challenge object for a game I'm building. There are many challenges. The constructors for each Challenge class derivation are different, however there is a common interface among them, defined in the base class.
When I call manager.CreateChallenge(), it returns an instance of Challenge, which is one of the derived types.
Ideally, I would like to keep the code for the object construction inside the derived class itself, so all the code related to that object is co-located. Example:
class Challenge {}
class ChallengeA : Challenge {
public static Challenge MakeChallenge() {
return new ChallengeA();
}
}
class ChallengeB : Challenge {
public static Challenge MakeChallenge() {
return new ChallengeB();
}
}
Now, my ChallengeManager.CreateChallenge() call only needs to decide the class to call MakeChallenge() on. The implementation of the construction is contained by the class itself.
Using this paradigm, every derived class must define a static MakeChallenge() method. However, since the method is a static one, I am not able to make use of an Interface here, requiring it.
It's not a big deal, since I can easily remember to add the correct method signature to each derived class. However, I am wondering if there is a more elegant design I should consider.
I really like the pattern you are describing and use it often. The way I like to do it is:
abstract class Challenge
{
private Challenge() {}
private class ChallengeA : Challenge
{
public ChallengeA() { ... }
}
private class ChallengeB : Challenge
{
public ChallengeB() { ... }
}
public static Challenge MakeA()
{
return new ChallengeA();
}
public static Challenge MakeB()
{
return new ChallengeB();
}
}
This pattern has many nice properties. No one can make a new Challenge because it is abstract. No one can make a derived class because Challenge's default ctor is private. No one can get at ChallengeA or ChallengeB because they are private. You define the interface to Challenge and that is the only interface that the client needs to understand.
When the client wants an A, they ask Challenge for one, and they get it. They don't need to worry about the fact that behind the scenes, A is implemented by ChallengeA. They just get a Challenge that they can use.
You're "decentralizing" the factory, such that each subclass is responsible for creating itself.
More commonly you would have a central factory that would know about the possible subtypes and how to construct them (often enough, simply by creating a new instance and returning that instance typed as a common interface or common base class). That approach avoids the issue you currently have. I also see no benefit to your current approach. You are currently gaining no encapsulation or code reuse over the more typical implementation of a factory.
For additional reference, have a look at
http://www.oodesign.com/factory-pattern.html
Not necessarily the answer you are looking for but...
You can use following implementation, if you can move away from static method per class.
using System;
public class Test
{
public static void Main()
{
var c1 = ChallengeManager.CreateChallenge();
var c2 = ChallengeManager.CreateChallenge();
//var c = ChallengeManager.CreateChallenge<Challenage>(); // This statement won't compile
}
}
public class ChallengeManager
{
public static Challenage CreateChallenge()
{
// identify which challenge to instantiate. e.g. Challenage1
var c = CreateChallenge<Challenage1>();
return c;
}
private static Challenage CreateChallenge<T>() where T: Challenage, new()
{
return new T();
}
}
public abstract class Challenage{}
public class Challenage1: Challenage{}
public class Challenage2: Challenage{}
Let's say in C# I have a class called A
public class A : IInterfaceA
{
[Dependency]
B _b;
}
Then in B class I have a constructor like this:
public class B
{
...
public B(string someParam) { ... }
...
}
Now, I register class A like this:
_unityContainer.RegisterType<IInterfaceA, A>("RegistrationA");
and to resolve the interface I do:
_unityContainer.Resolve<IInterfaceA>("RegistrationA", new ParameterOverride("someParam", "The param."));
Now I want to know if it is good practice to resolve the class and pass the parameters like this or I should do it another way.
Thanks a lot :)
First of all the code you posted does not work: in fact you're overriding the parameter of class A, while in your code the constructor with the parameter is B.
Generally speaking, using parameter override is not a good practice in my opinion (unless some very specifical context like a console application or a web service using an existing container but it's avoidable in most cases) for these reason:
Using Resolve looks like a Service locator: anti-pattern nowadays. You will find a lot of discussion googling about.
Using ParameterOverride means that the client (the caller of Resolve) knows exactly the type mapped in the container and wants that type initialized with a specific parameter. But this is just the opposite of inversion of control.
The best way is to use an abstract factory. You can add in your code and use a more flexible and SOLID abstract factory:
public interface BFactory {
B Create(string bparam);
}
public class BFactoryUnity : BFactory {
private IUnityContainer container;
public BFactoryUnity(IUnityContainer container) {
this.container = container;
}
public B Create(String bParam) {
var b = new B(bParam);
container.BuildUp(b);
return b;
}
}
So you can register:
_unityContainer.RegisterType<IInterfaceA, A>("RegistrationA")
.RegisterType<BFactory, BFactoryUnity>();
Now the client can resolve only the factory and use it:
var bFactory = _container.Resolve<BFactory>();
var b = bFactory.Create();
Now, in a big application you will need a lot of similar factories. To avoid the boilerplate code of abstract factories and implementations you can find in the web some implementation of automatic abstract factory extensions.
When writeing unit tests for a single class that contains other objects what's the best way to use
mock objects to avoid tests dependant on other classes.
Example 1:
public class MyClass
{
protected MyObject _obj;
public MyClass()
{
_obj = new MyObject();
}
public object DoSomething()
{
//some work
_obj.MethodCall();
//more work;
return result;
}
}
I'd rather not expose the protected value to create a unit test for the code. A wrapper class would
work for testing but is there a better way?
Example 2:
public class MyClass
{
public object DoSomething()
{
//some work
MyObject obj = new obj(parameters);
_obj.MethodCall(Method1);
//more work;
return result;
}
public int Method1()
{ ... }
}
Similar to the above example but the ojbect is created in the method I am calling.
Example 3:
public class MyClass
{
public object DoSomething()
{
//some work
obj.MethodCall(Method1);
//more work;
return result;
}
public int MethodA()
{ ... }
}
Is there a way to test MethodA when it is only used as a delegate?
I recommend that you take a look at dependency injection. One thing is using mock objects, but unless you're using something like TypeMock, which basically lets you modify you code on the fly, you want to have a way to inject the instances your class depends on if you want to get rid of the dependencies. So in examples 1, I would suggest that instead of newing an instance of MyObject in the constructor, you could have the caller supply that instance. In that case you would easily by able to replace it with a mock or even a stub.
Have you tried deriving a UTMyClass from MyClass?