So I'm just getting used to mocking stuff. I have this private variable here:
private CoreDataContext _coreDataManager;
On this class:
public class RatesControlReport
: Chatham.Panda.Batch.ProcessDefinition.BatchProcess
This class has a void method on it that I want to test called CheckSwaptionVols(DateTime runDate).
In the first part of my test I can instantiate the main class:
RatesControlReport ratesControlReportProcess;
ratesControlReportProcess = new RatesControlReport();
And basically I want to make this call:
ratesControlReportProcess.CheckSwaptionVols(DateTime.Now);
However this method uses the private variable like so:
System.Data.Linq.ISingleResult<CheckSwaptionVols> swaptionStatusResult = _coreDataManager.CheckSwaptionVols(this._runDate);
I'd love to be able to pass in a mocked version of this variable instead and return my own specified System.Data.Linq.ISingleResult<CheckSwaptionVols> so the test can continue without a dependency on the DB.
How would I do this?
Well, it depends on where you instantiate your CoreDataContext. If this is constructed in a static context, or in the constructor, there's really no way to create a mock for it. This is why it is generally considered bad practice to instantiate dependencies inside the object. What you need to do is provide some method of dependency injection. This can be as simple as an overloaded constructor:
public RatesControlReport(CoreDataContext context)
{
_coreDataManager = context;
}
...or even an internal method if you're desperate:
internal void InjectContext(CoreDataContext context)
{
_coreDataManager = context;
}
Generally speaking, however, it is considered best practice to always provide your CodeDataContext object when constructing your RatesControlReport. This will separate the data access from the business logic, which will allow you to unit test both classes more effectively.
Related
Class Myclass
{
public void CalculateShippingCost()
{
/// Some line of codes.
var discount= new Discount();
discount.GetDiscount();
/// Some other functionality
}
}
here I want to mock discount.GetDiscount() call as it make a service call .And I don't want to expose this discount object outside this method .
As you've found, having a new statement in a method makes it hard to unit test it. The usual thing to do in this case is to inject the dependency into the class like this
As Mark points out in the comments, you can't just mock Discount since you can't have 2 classes with the same name. So what you can do is make an interface that defines what Discount does. Then your real Discount class and your mock can both implement that interface.
In your MyClass class you then depend on the interface rather than the class.
interface IDiscount
{
void GetDiscount();
}
Class Myclass
{
private readonly IDiscount _discount;
public Myclass(IDiscount discount)
{
_discount = discount;
}
public void CalculateShippingCost()
{
/// Some line of codes.
_discount.GetDiscount();
/// Some other functionality
}
}
By doing it this way, you can create a mock of the IDiscount interface and pass it to MyClass when you instantiate it.
If you have a small number of classes, you can do this dependency injection by hand. If you have a lot of classes, you can consider using a DI container to handle it for you.
How to mock a variable that is created inside a method?
As far as I know you can't. A variable that is declared inside a method only exists within that method so there is no way to influence/manipulate that variable outside of the method.
That said there are ways to implement what you want while still following dependency injection practices.
Here are the steps I would personally take:
Create an interface for Discount (if you haven't done so already). Lets call this one IDiscount.
Create a factory that can produce that IDiscount. It's interface could look something like this:
public interface IDiscountFactory
{
IDiscount CreateDiscount();
}
(apologies, for some reason the Code Sample layout is bricked for me and can't get it to work. Edit: If I comment-block it as well at least it also does the code formatting)
Inject this factory into your class store it in a private readonly variable and inside your CalculateShippingCost method you can call: var discount = _discountFactory.CreateDiscount();
This way the actual Discount is only used inside your method, but you can still mock the IDiscountFactory (and therefor the IDiscount it produces)
I'm studying Microsoft Fakes to implement unit tests in a project of mine.
If i've understood correctly, i use stubs to set the behavior of external components (that implement interfaces) that the main component i want to test is dependent from.
I use shibs to simulate the behavior of specific pieces of code at runtime.
My goal is to test a method of a manager class that has dependencies to other components all implementing interfaces. This method, among the other things, calls a private method.
In the test method i need to force the result of that private method.
The scenario is similar to the following code:
public class MyManager : IMyManager {
private IMyDependentManager _myDependentManager;
public MyManager(IMyDependentManager myDependentManager) {
this._myDependentManager = myDependentManager;
}
public void MyMethodToTest(data1, data2,...) { // method to test
...
byte[] res = MyPrivateMethod(data1); // i want to set the result of this method in order to NOT execute it, otherwise the test will fail
...
}
private byte[] MyPrivateMethod(data1) {
}
}
Any suggestion on how to setup the test would be very helpful.
The implication from the question and the private method's signature is that you need to separate the concerns.
Consider what the responsibility of your manager class is. Now consider what that private method is doing. I suspect you will find that the private method is not something that the manager class is (directly) responsible for - it is doing something that the manager should be delegating.
Move that private method into a separate class (as a public method), and use dependency injection to give it to the manager class, I would suggest doing this via an interface.
Now when testing your manager, you can supply it's constructor with a mock of the new class's interface to return whatever you like.
From unit testing and dependency injection point of view, what's the usual adopted norm when it comes to helper methods?
Here is my example situation:
public class GoodiesController : Controller
{
private IMyContext _context;
public GoodiesController(IMyContext context)
{
_context = context
}
public async Task<IAction> GetThoseGoodies()
{
if(YouLikeThemThisWay(Request.Path))
{
var result = await _context.GoGetThemThisWay()
} else { }
}
My question is am I better off with YouLikeThemThisWay(string path) as a static helper in some class or as a private instance method? Assuming I might have a couple of the likes of YouLikeThemThisWay?
It really depends on what your YouLikeThemThisWay(string path) method does. My rules for using a static method or as follows:
Does it require a non-primitive dependency? If so, don't use static.
Does it affect the state of the application? If so, don't use static.
Does it extend the functionality of a class or type you do not have access to internally (IE BCL classes or primatives)? If so use a static extension!
Will it impact unit tests--as in make them more difficult--if I cannot mock the routine? If no, then make it static!
Will it be used by more than one type or class? If so that it makes it a better candidate for static!
Does the routine perform some sort of IO, like calling a database or the filesystem? If so, I would not make it static.
Basically, small helper functions that are easily tested and don't affect state or usually OK to make static. If there is state involved, the routine requires a dependency that you would normally inject, or the routine is making IO or IPC calls then do not make it static.
One caveat to the dependency issue is technically you could use method injection to handle the dependencies, but I like to keep it simple. Your method is probably OK to be static.
Reuse is a big factor in statics too. If the routine will only be used in one class, it may be pointless to make static. Most of my static methods live in helper classes that are easily accessed anywhere.
EDIT: Note that I usually require most or all of those five rules to favor statics in order for me to even consider making something static.
I have this scenario: an interface with 2 methods
the 2 methods take requests and return response
Methods contain functionality inside (check permissions and validate request and get data from database using entity framework.
But I want to test the methods and not just the interface.
I've tested the interface successfully but now I want to enter the method and test inside it.
Code example:
public interface IMyInterface
{
[OperationContract]
responseObject GetData(Service<RequestObject> request);
}
public class MyConcreteClass : IMyInterface
{
public responseObject GetData(Service<RequestObject> request)
{
CheckForNull(request);
ValidateMethod(request);
//connect to db
using(var context = new contextEntity)
{
//get data
}
}
}
Now, I want to test the check nulls, permissions and data access, is it possible? Or do I have to extract interface from the internal methods?
PS, this is for my unit testing. I'm trying to eliminate external dependencies.
please explain in detail
Unit testing private methods should not be needed directly, only indirectly via public methods. If you think you testing a public method isn't enough precise, it might be that the method and the class are too complicated already.
In that case consider creating one or more new classes where the new code is located. That way you can unit test your code via public method. The added benefit is that your code is probably better in terms of Single responsibility principle.
The reason for mocking is so that you can control behaviour; in this case, I'm going to go out on a limb and guess that Service<RequestObject> doesn't actually have any behaviour, and therefore it doesn't actually need to be mocked. So it can probably just be passed as-is in any tests.
However, if it does have behaviour, and that behaviour crosses an architectural boundary (let's say in the GetData method you are calling some method on the request parameter that will make a network call, or access the file system, etc.) then you do need to mock it. But you can do that easily enough:
public interface IService<RequestObject>
{
//put method and property signatures of Service<RequestObject> here
}
public class ServiceObject:Service<RequestObject>, IService<RequestObject>
{
public ServiceObject(RequestObject request): base(request){
//or however the Service<Request> object is instantiated.
};
}
Then change GetData to take an IService<RequestObject>; now your calling code can instantiate a ServiceObject in place of a Service and pass it to the GetData method. Plus you can Mock any methods on the interface as you need. Obviously if you don't control the calling code, that's a problem since whoever is writing that code needs to do it, but that's a conversation you will need to have with them :)
In terms of testing the internal operations,you need to look at how you can abstract any dependent behaviours used by the GetData method - for example, the contextEntity, the CheckForNull, the ValidateMethod, etc - all of these are candidates to be extracted into their own abstractions and injected into the MyConcreteClass as dependencies, e.g.:
public class MyConcreteClass: IMyInterface
{
readonly INullChecker _nullChecker;
readonly IValidator _validator;
readonly IContextEntity _context;
public MyConcreteClass(INullChecker nullChecker, IValidator validator, IContextEntity _context)
{
_nullChecker = nullChecker;
_validator = validator;
_context=context;
}
public responseObject GetData(Service<RequestObject> request)
{
_nullChecker.Check(request)//**;
_validator.Validate(request);
var result = _context.DoSomethingWith(request);
return result;
}
}
Now you can write tests for MyConcreteClass and use mocked implementations of the dependencies, to ensure that the GetData method correctly uses them.
**and I will guess that this can be replaced with a simple if request==null throw new ArgumentNullException() which is cleaner and simpler anyway.
I am really interested in some architectural methods. I like DI and IOC, but I don't understand costructor injection; why is it so complicated. I've written the code below which uses constructor injection:
namespace DependencyInjection
{
class Program
{
static void Main(string[] args)
{
ConstructorInjectionClass myCtx = new ConstructorInjectionClass(new PdfFormat());
myCtx.Print();
Console.Read();
}
}
public interface IFormat
{
void Print();
}
public class PdfFormat : IFormat
{
public void Print()
{
Console.WriteLine("Pdf Format Print is completed...");
}
}
// Constructor Injection
public class ConstructorInjectionClass
{
private IFormat _format;
public ConstructorInjectionClass(IFormat format)
{
_format = format;
}
public void Print()
{
_format.Print();
}
}
I've written some code below. I think it's simple.
public interface IFormat
{
void Print();
}
public class PdfFormat : IFormat
{
public void Print()
{
Console.WriteLine("Pdf Format Print is completed...");
}
}
public interface ISave
{
void Add();
}
public class Sql: ISave
{
public void Add()
{
Console.WriteLine("Adding to SQL is completed...");
}
}
// Constructor Injection
public class ConstructorInjectionClass
{
public ConstructorInjectionClass(IFormat format)
{
format.Print();
}
public ConstructorInjectionClass(ISave saver)
{
saver.Add();
}
Why should I use constructor injection? Advantages or disadvantages of these two methods?
The first example is constructor injection. You are injecting the class with the responsibility for printing into the class.
In the second example you are creating a new class with one of 2 arguments and using the argument in the constructor. This is bad for several reasons:
Your constructor should not really do significant work, this is either saving or printing in the constructor
Your different constructors are doing different this. The constructor should only create a new instance of your class.
It is not clear that the different constructors will actually do something when they are given different objects.
If you pass the objects to the constructor and then it just calls them, why would you not just have the code that is constructing this class call the methods on ISave and IPrint implementations. After all it must have them to be able to pass them to the method. If your object holds these internally then they could have been provided when your object was constructed (like in your composition root) and the client code that calls Print on your object would not need to know anything about the fact that the ISave and IPrint implementations exist,
Constructor injection is about you class asking for the dependencies it has in it's constructor, so it is clear what the dependencies are. By requiring the dependencies rather than creating them it becomes simpler to test the class as you can inject mock dependencies for testing purposes.
The first option is good, and if you want to add saving then you should add an extra argument to the constructor to take a ISave interface as well as the IPrint interface and have a method Save which will delegate to the ISave implmentation.
By having the dependencies injected and by programming to an interface it makes it easier to change the functionality later on. You could, for example, make it pring to a file easily (by changing the IPrint interface you pass in or change it to save to an xml file or a webservice by changing the ISave implementation you pass it. This make you class loosely coupled to the save and print implemenations
I would read this excellent answer for more guidance on DI/IOC
Well, as with any pattern, constructor injection should be used when and only when it's a good idea to use it. Your example code is kind of strange...
Your first example is spot on. Your class has a method called Print which has a dependency on another class to do the printing. Rather than instantiate this dependency, it requires that the dependency be supplied in its constructor. This is a classic example of the Dependency Inversion Principle. Basically: "Require, don't instantiate."
Your second example isn't quite clear, though. What is your class really doing? What's it for? It has two constructors which perform an action on their dependencies, but why? Nowhere else in the class is there a dependency on instances of these types. So why have the wrapper class in the first place? It seems more... contrived... than your first example. It's unclear what the architecture of the code is trying to accomplish, and therefore as it stands not a good use of constructor injection.
Lets say that you want to inject dependencies... you could do this via constructor injection or via property setters. I think one of the advantages to constructor injection is that IOC's use this strategy. So if you aren't sure you want to go IOC but you want to do DI then should probably use constructor injection to make the transition to IOC latter... easier... if you should change your mind...