Skip to main content

Can we mock an extension method?

Pentru teste mai mult ca sigur ati folosit un framework petru a face mock pe diferite obiecte. In general am folosit Moq pentru a putea face mock la date. Este destul de usor de folosit, mai jos puteti sa gasiti un exemplu:
Mock<IService> serviceMock = new Mock<IService>();
    .Returns(()=> new Result());
Mai sus am creat un mock pentru IService, iar in momentul in care se apeleaza metoda Call cu orice parametru de tip string, se returneaza un nou obiect de tip Result.
Nimic deosebit pana acuma. Dar ce se intampla daca vrem sa facem mock la un extension method. Vestea proasta este ca nu se poate face. Majoritatea framework-urilor pentru mock-ing nu suporta aceasta functionalitate.
Cea mai buna solutie este sa refactorizam codul daca putem. Dar exista cazuri cand acest lucru nu il putem face sau extension method nu este declarat de noi si vine dintr-un assembly exterior.
O solutie comuna, care poate sa fie folosita atat pentru aplicatiile .NET classic, Silverlight, WP7, ... este sa injectam actiunea care apeleaza metoda noastra. De exemplu putem sa extragem intr-un Action actiunea care apeleaza extension method, iar aceasta sa fie injectata prin contructor folosind un factory de exemplu. O alta varianta este sa facem un wrapper peste clasa noastra.
Urmatoarea solutie nu functioneaza pe Silverlight din pacate. Ar fi fost nice sa fie suportatat macar in versiunea 5, dar nici o sansa. Solutie se refera la folosirea Microsoft Moles. Prin intermediul acestui framework putem sa inlocuim orice clasa, metoda cu un mole care sa faca ce vrem noi. Un mole, intercepteaza apelul spre o anumita metoda si se poate executa orice alt cod. Putem sa facem mole la orice fel de metoda, atat statica cat si extension method.


  1. Un extension method nu e decat o metoda statica, deci nu e de mirare ca majoritatea frameworkurilor de mocking care lucreaza cu metode "ortodoxe" nu au cum sa creeze un mock pentru asa ceva..

    Si Moles sau Typemock Isolator pot sa mockuiasca o metoda statica pentru ca se baga cu CLR profiler-ul si rescriu IL-ul, si alte ghidusii de genul.

  2. Partea interesanta este cand ai un proiect Silverlight si nu ai aceste optiuni.
    Daca ar fi sa aleg intre Moles si Moq as alege Moq, dar uneori nu ai de ales, sau in cazul asta numarul de optiuni este egal cu 0.

  3. Da, in cazul acesta daca mocking framework-ul nu are versiune de Silverlight, cam singura optiune e un adapter sau refactoring daca e posibil..

  4. Am ajuns la o solutie asemanatoare. Putin de refactoring, un factory impreuna cu un adaptor. O sa revin maine cu implementarea exacta.


Post a Comment

Popular posts from this blog

ADO.NET provider with invariant name 'System.Data.SqlClient' could not be loaded

Today blog post will be started with the following error when running DB tests on the CI machine:
threw exception: System.InvalidOperationException: The Entity Framework provider type 'System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer' registered in the application config file for the ADO.NET provider with invariant name 'System.Data.SqlClient' could not be loaded. Make sure that the assembly-qualified name is used and that the assembly is available to the running application. See for more information. at System.Data.Entity.Infrastructure.DependencyResolution.ProviderServicesFactory.GetInstance(String providerTypeName, String providerInvariantName) This error happened only on the Continuous Integration machine. On the devs machines, everything has fine. The classic problem – on my machine it’s working. The CI has the following configuration:

TeamCity.NET 4.51EF 6.0.2VS2013
It seems that there …

Entity Framework (EF) TransactionScope vs Database.BeginTransaction

In today blog post we will talk a little about a new feature that is available on EF6+ related to Transactions.
Until now, when we had to use transaction we used ‘TransactionScope’. It works great and I would say that is something that is now in our blood.
using (var scope = new TransactionScope(TransactionScopeOption.Required)) { using (SqlConnection conn = new SqlConnection("...")) { conn.Open(); SqlCommand sqlCommand = new SqlCommand(); sqlCommand.Connection = conn; sqlCommand.CommandText = ... sqlCommand.ExecuteNonQuery(); ... } scope.Complete(); } Starting with EF6.0 we have a new way to work with transactions. The new approach is based on Database.BeginTransaction(), Database.Rollback(), Database.Commit(). Yes, no more TransactionScope.
In the followi…

Fundamental Books of a Software Engineer (version 2018)

More then six years ago I wrote a blog post about fundamental books that any software engineer (developer) should read. Now it is an excellent time to update this list with new entries.

There are 5 different categories of books, that represent the recommended path. For example, you start with Coding books, after that, you read books about Programming, Design and so on.
There are some books about C++ that I recommend not because you shall know C++, only because the concepts that you can learn from it.


Writing solid codeCode completeProgramming Pearls, more programming pearls(recommended)[NEW] Introduction to Algorithms


Refactoring (M. Fowler)Pragmatic ProgrammerClean code[NEW] Software Engineering: A Practitioner's Approach[NEW] The Mythical Man-Month[NEW] The Art of Computer Programming


Applying UML and Patterns (GRASP patterns)C++ coding standards (Sutter, Alexandrescu)The C++ programming language (Stroustrup, Part IV)Object-oriented programming (Peter Coad)P…