How to mock datacontext (LINQToSQL) which is part of another assembly? - unit-testing

I am using LinqToSQL in my project.As pert of my unit testing, I am trying to mock datacontext which is part of another assembly which is referenced in the ASP.NET WEB API project.
Based on the following URL:
http://weblogs.asp.net/rashid/100-unit-testable-linq-to-sql-repository
I tried to create a partial class for the datacontext but somehow it is not working.
Can anyone help me to know how to mock the datacontext class which is part of another referenced assembly.

Right from what I can gather from skim reading that article is that it's mostly call assertion and there are no tests around queryable results. IMO these tests are pretty meaningless and more over when you start putting in meaningful tests it wont work because Linq-to-sql is not mockable, DbContext is not mockable, can't use pocos, etc. This article was written in 2009 and Linq-to-sql is not a current product.
How big is the project? If at all possible move to EF6 and utilise either IDbSet to create a FakeDbSet or Mock the DbSets themselves and alot of the methods are virtual now. Have a look at this Q&A:
How are people unit testing with Entity Framework 6, should you bother?
If you search for Unit testing EF6 you find what your're trying to achieve much easier.
If you really can't change the Ling2Sql then use a façade pattern and compose you DbContext inside this. The façade would expose the DbSet are IQueryable and wrap up any method calls. This means though that you would have to create methods and properties that are virtual and then you can mock the façade. Alternatively you could also create an interface for the facade which you can also use for mocking. This would make any complex queries you write completely testable but you are creating code that calls other code. You would also have to watch the lifestyle of the façade as this is newing up the DbContext. This pattern is used to get round testing where AppSettings are involved, it's the same thing really. You just creating something that is mockable as a wrapper for something that isn't.

Related

Create a simple unit tests framework from scratch in Coldfusion

I know there are existing tools for testing a ColdFusion application (MXUnit, MockBox), but I'm creating a custom tool, so that it will require less configuration.
When I run a unit test file, it's done via a generic 'model' which retrieves all functions from the unit test file. Within each test function, I have to call assertEquals -- but these functions are in the model, so I cannot access them.
I tried by passing the model itself to the unit test file so it can call the models functions directly but it doesn't work and it adds logic to the test file, which I don't like.
I can also extend the model in the test file but I will have to call directly the test file, call super.init(this) so the model can fetch test functions, etc..
Is there a way to achieve this kind of process? What's the best option?
In answer to your question, it sounds like you want to inject variables / methods into the subject under test. You can do it like so:
myInstance["methodName"] = myFunction;
You can then call the injected method like so:
myInstance.myFunction();
Both MXUnit and TestBox use this technique.
Having said that I don't quite understand why you want to re-invent the wheel. TestBox is an excellent, proven testing framework which has a wealth of features which would take you an incredible amount of time to replicate. I'm not quite sure what the configuration issue you have could be - it really doesn't require very much setup. Maybe it might be worth asking how to setup and use TestBox rather than how to build your own testing solution :)
There is a good book (which is available in a free version) which you can read on TestBox here : http://testbox.ortusbooks.com/
Good luck!

Unit testing real server data exchange?

I'm working on a project that has client and server side. And I'm writing a "pre-check-in" tool that will validate a lot of our communication between client and server.
I already have unit tests on both sides, now I really want to test the integration between both.
Like a real client connection to the server and vice-versa.
I really want to go unit testing on this, but I'm having a really hard time figuring out how I can initialize the MMVMCross framework and my view model classes.
In another thread I've asked for help on my "console app" that runs the tests but it is also really hard to initialize the framework and it makes me loose the coolness of unit testing with Visual Studio and reSharper.
My view models use SQLite and HttpClient with async/await.
For instance: I can't find a way to instantiate a view model that would need this interfaces:
IChatService, IMvxMessenger, IDataService, ISettingsService
Some from the framework some from my own code.
I known and I'm trying to register my ones, on a TestFixtureSetUp, but off course this fails, as the MVVM base subsystem (ioc?) is not setup yet.
Some above services, like IDataService for instance, also needs ISQLiteConnectionFactory, IMvxMessenger, ISettingsService.
I know unit testing is supposed to be fast, but my idea is to put all this tests in a new Category, that I would run only before my check-ins and my buddy, server developer, would run before his check-ins.
What would be the best approach here?
Any hint, suggestions, things to investigate/study would help at this point, as I'm practically stuck on this one.
Sergio
For instance: I can't find a way to instantiate a view model that would need this interfaces:
IChatService, IMvxMessenger, IDataService, ISettingsService
Generally this would be done using Mock implementations and then calling the ViewModel constructor directly with those Mocks.
I'm having a really hard time figuring out how I can initialize the MMVMCross framework
In order to initialise the IoC part of the framework you can use the MvxIoCSupportingTest helper class -https://github.com/slodge/MvvmCross/blob/v3/Cirrious/Test/Cirrious.MvvmCross.Test.Core/MvxIoCSupportingTest.cs
If you then need additional parts of the framework, then generally you should mock these in some way. For example, see how navigation is mocked in these two articles:
http://blog.fire-development.com/2013/06/29/mvvmcross-enable-unit-testing/
http://slodge.blogspot.co.uk/2013/06/n29-testing-n1-days-of-mvvmcross.html
If it helps, an example of this type of test is https://github.com/slodge/MvvmCross-Tutorials/blob/master/Sample%20-%20TwitterSearch/TwitterSearch.Test/TwitterViewModelTest.cs#L21
If this answer doesn't have sufficient information, please provide a bit more example code about the tests you are trying to write.

How can unit-tests use SmartGWT classes?

In our SmartGWT web application, we pass our domain objects from the server to the client and back (via GWT serialization). To show/edit the data at client side in a DynamicForm or a GridList, we have to convert it into a Record (or ListGridRecord) and after editing back into our domain objects.
I would like to write a unit test for this conversion method, but a straightforward attempt in JUnit fails, since the record's getAttribute and setAttribute methods are implemented by JSOHelper.getAttribute/JSOHelper.setAttribute, which are static methods declared as native and implemented by JSNI in JavaScript, thus only usable on the client side, when compiled to JavaScript.
We get an UnsatisfiedLinkError when using these methods from JUnit, as the native methods are not implemented there.
Any ideas how I could test these classes?
These critical methods could be easily implemented by a simple HashMap (or maybe a LinkedHashMap, if the attribute order is important) - actually a JavaScript object is about that, if only looking at the data part, not the methods. Thus I just think about providing an alternative implementation of some selected SmartGWT classes (mainly JSOHelper) with Java implementations instead of the JavaScript ones.
But am I really the first one who has this problem? Am I simply too stupid to find the existing solution?
If you have used a MVP or MVC pattern in your code, just mock the view code with something like mockito and test all the rest of the application. To test the view code you will need to use something like Selinium I don't think gwtTestCase would work with smartGWT since it is just a gwt wrapper around js code.

phpUnit and models which inherit ADODB_Active_Record, stubbing ADODB_mysql

I've searched high and low and, astonishingly, cannot find an answer.
When trying to unit test my models with phpUnit how can I stub the database?
I'm using a PHP framework CMS which has a number of classes which inherit from a class ("Model") which inherits from ADODB_Active_Record. Model's constructor grabs a db object (from ADOConnection) and passes it to Active_Record's constructor.
It might not be Best Practice, but in order to change the code as little as possible, I'm thinking of tweaking grabDBObject() to return a stub object when in testing. That stub gets passed to ADODB_Active_Record, and, in theory, I can test my models.
However, I can't figure out how to create the stub. ADODB_Connection isn't simple. It's not going to be a matter of replacing Execute(). There are a bunch of other functions, like qstr(), that it appears I'll have to worry about and rewrite as necessary.
What's surprising is I can't find any discussions of people doing this. This has got to be a common problem. Am I going in the wrong direction? I understand that I can use something like dbUnit to actually do db queries rather than stubbing ADODB_connection, but I also understand that I should stub as much as possible, and that it's bad to rely on a db for unit tests of a model's methods.
So,
1. Should I be stubbing the db connection for unit testing?
2. How?
Have you tried the getMock() method of phpunit ?
It allows you to provide a fake object for testing, without touching your production code.
But in that case, you have to build the expected result by yourself.
The doc is here :
http://www.phpunit.de/manual/3.0/en/mock-objects.html

EF4.1 DbSet vs. EF4 ObjectContext and Unit Testing

I currently have a project I've started with EF4, and am going back and adding in unit testing after the fact. I am using the EF4 POCO T4 templates with my model (database) first context. I am using generic repositories for my DAC logic, and unit of work pattern for persistence.
However, I'm running into some issues understanding how to mock up the ObjectContext/ObjectSet. I looked at using the FakeObjectSet<T> sample from this article, but it still leaves a few things out, such as auto-incrementing identities and transaction rollbacks.
So, I'm trying to find a good EF design that will still be fully unit testable.
My question is, does EF4.1 DbSet solve a lot of the issues w/ unit testing EF4? Are there any good comprehensive articles for designing EF4.1 solutions that are fully testable?
Also, keep in mind that I need a model-first solution.
Thanks in advance.
Fully simulating behavior of mocked layer is not point of unit testing. The point of unit testing is believing that mocked layer simply works. Unit test verifies the tested method not the mock. You will just verify that correct method on the mock were called and perhaps you will set up some callbacks for modifying passed data if your business logic expects some values. Example:
You have a business method inserting the record to the database and using the entity and its Id after insertion. The IObjectSet mock will be configured to:
Set expectation that AddObject was called only once - you can set the expected instance in the verification
You can define callback for AddObject to set Id to some value and use it later in the test
DbSet will not make any difference - it is just wrapper around ObjectSet with similar behavior. In my opinion there is no efficient way to make mocks behave as real EF. The effort needed for creating mock with behavior simulating EF + database will be much bigger then effort for your whole application! That will not be mock anymore it will be fake EF provider.
If you want to test your EF code (mapping, querying, persisting) and database behavior (like auto-increment, transactions, etc) you have to write integration tests. Here you have some related questions discussing repositories, unit of work and challenges with testing:
ASP.NET MVC3 and Entity Framework Code first architecture
Organizationally, where should I put common queries when using Entity Framework Code First?