I'm relatively new to EntityFramework and really want to get into testing things before I get too much further into things and have a huge codebase to retrospectively write tests for. I've not used it much and so methods are fairly basic, like below;
public Employee GetEmployee(int employeeID)
{
using (DatabaseContext db = new DatabaseContext())
{
return db.Employees.SingleOrDefault(e => e.idEmployee == employeeID);
}
}
This is fine in my app, but in my test project, it doesn't work because the test project doesn't seem to read the app.config file and so there's no connection string for DatabaseContext to use. I've read a bit about testing, nothing seems really definitive, though this post is the "official" way to do things (it's linked to from MSDN. The post seems fairly involved though and would require me to do things a lot differently than what I currently am, unless I've misunderstood some of it?
Could someone help clear this up for me? I can't even cheat and copy app.config across to the test project, it still doesn't read it (I've also tried renaming to MyApp.exe.config and still no luck). Is my GetEmployee method wrong? Should I do something more like the linked post? Or is there some way to test that I've not found yet?
#FizzBuzz - here is another article the discusses how to setup your unit test projects to work with entity framework:
How to get Entity Framework to read my app.config file in Unit Test project
You can read one approach for integration testing here.
About the config issue setting Copy to Output Directory property to Copy Always should do the work.
There are to options to resolve the issue you are facing.
Option 1: Create a mock for the app.config values. for mocking you can use Rhino Mock
Option 2: In your Unit Test project : Right click on the project > Add > Existing Item >
Select File > Add it as a link.
If you don't want to go with your live database (and right so!), then you basically have two options:
Use another database (must be of the same kind as your live db,
since EF doesn't allow for changing the db system, only its
location) and add another app.config to your unit test project
(which is the same as in your live project except that the db
connection string is different).
Use the NDbUnit framework, which
allows for defining the data in xml files. Here also you'll need an
individual app.config for your test project, if you don't want to hardcode the test data connection string. (This approach is only
advisable, if your live db has no or only very few schema changes,
because NDbUnit is quite allergic to these.) I wrote a blog post (with sample solution) about this approach here.
A third approach would be to mock all EF stuff, but this quickly gets overly complicated (you can find this also in a previous part of the above mentioned post, if you're interested).
HTH
Thomas
Thanks for the information people, found some interesting hints and tips through the various links supplied. In the end, I tried out this article from MSDN, funnily enough! Though it says it's for EF6, it does actually work for previous versions. The reason it indicates EF6 is for async stuff.
Related
So I am wrestling with this for quite some time now, but I can't seem to figure it out.
At first I had a datalayer in my solution. This layer is for the communication between the business and the database. It had a generic repository and context objects so it is easy to retrieve and send data from and to the database with EntityFrameWork 6. This all worked very good... but...
Now I notice that in my application (WebAPI 2) I need to change database at runtime. This is really hard to do. It should follow this path:
An external application does a call to my API. In the header of the request is set which database should be used (an Id, or a logic name or whatever, not important now). Before an action is executed some code should read this header-item and set the new connection to the repositories.
This is how I register the repositories for Unity:
container.RegisterType<IContexts.ILanguageCodes<LanguageCode>, Data.LanguageCodes>();
container.RegisterType<IContexts.ISecurityRoles<SecurityRole>, Data.SecurityRoles>();
To show you everything what the implementations of these interfaces are is very much.
To change the connection to an other database I have to change the DBContext, which I know where to find, but the code doesn't. So I started Googling.
Then I found this article: http://rob.conery.io/2014/03/04/repositories-and-unitofwork-are-not-a-good-idea/. I read it and all the stuff that is not good is in my project. I was like: Okay, lets start over on the datalayer.
THen I found this article: https://www.danylkoweb.com/Blog/a-better-entity-framework-unit-of-work-pattern-DD. I followed this and came pretty far. But got stuck on the part where the request comes in.
So basicly I am looking for this:
A way to change the connection to an other database at runtime with dependency injection, so I don't have to change the connection everywhere. In the end; the idea of DI is that you don't know where the implementation is, so in this case you don't know where all the connections are.
Does anybody have an example found on the internet I could use to try? Or maybe a good, small example I can focus on?
Long story, I hoped I could make it smaller. I hope someone can help me with this.
Thanks
When I need to support scenarios like this I have one "provisioning" or "configuration" database which holds the connectionstring for each customer/user/whatever. This is separate from the databases which map to the data my application needs.
Whenever the requests comes in you can configure your IOC container with the correct connectionstring, altough I don't know if unity supports this scenario, I know AutoFac / Ninject and most other containers allow changing the container.
In my project, I trying to implement repository pattern and unit of work.
I found some web site to describe how to implement it such as:
http://www.codeproject.com/Articles/688929/Repository-Pattern-and-Unit-of
http://www.codeproject.com/Articles/561584/Repository-Pattern-with-Entity-Framework-using
I was wondering, why is not generic Unit of Work and Repositories Framework? then try several search on internet and I found it,
http://genericunitofworkandrepositories.codeplex.com/
This framework is first code but my project is model first therefore is not work correctly?
Could you please suggest me model first framework like this?
My project is a internet web site with one database, If there is plausible reason I can change model first approach to code first approach.
Thanks for you time.
We've abstracted all the interfaces in our latest release into Repository.Pattern project https://genericunitofworkandrepositories.codeplex.com/SourceControl/latest#main/Source/Repository.Pattern, in plans to implement nHibernate provider. You are more than welcome to start implementing these interfaces, based on bandwidth at the moment, I cannot commit to any dates as of yet.
I'm using Entity Framework 5 in my project. And I wanted to test some new funcionalities.
What happened is that eventhough my db is UPDATED, (when I add a migration it does not add anything else) and eventhough if I run my project it runs just fine. When I try to test the project with NUNIT I get this exception:
System.InvalidOperationException : The model backing the 'DbContext' context has changed since the database was created. Consider using Code First Migrations to update the database
Has any of you have this problem? If so how can I solve it?
Well, my original answer got deleted, guess because it wasn't really an answer as much as a statement that I had the same problem. At this point I have found an answer of sorts, so maybe this one will pass muster.
Of course, I only assume we are having the same issue, but it seems pretty likely since the symptoms are exactly the same. What I discovered is the connection string for my repository was not getting set correctly even though I had set it up "correctly" in a config file using the MyTestProject.dll.config naming convention. Seems like NUnit isn't using the connection string from the config for some reason.
I've set up a temporary solution where I use a different constructor that forces the correct connection string for my repository when creating it for NUnit. Easy to implement this since I'm using DI to create the repository and just need to ask the factory for a different flavor when testing. Working now to figure out why NUnit doesn't use the config file as it seems like it should.
Maybe not a complete answer, but at least this solution got me back to where I can test... We'll see if this one gets deleted.
I'm trying to improve the automated testing in my application, but am unsure of the best way to proceed.
My app gathers data from multiple forms, recodes it and stores it in a database. I have created a pretty complex SQL view, which flattens the structure out, so it can be imported into a stats package (SPSS).
My concern is that the view is complex, and I want to automate some tests around it.
Currently I have some functional tests, which create a complete form objects model, and sends it into the application. I then retrieve the view from the database, and use reflection to test that the retrieved view fields match the original data.
The problem is that this is very manual and heavy, my fixtures are lengthy, and it is cumbersome to add new scenarios (i.e. various parts of the model incomplete).
Does anyone have any advice on how I could improve my test strategy? Tips tricks all welcome!
Thanks!
DbFit is perfect for this. DbFit is an extension of FitNesse which maybe you are already using since you spoke of using "fixtures". In any case, DbFit makes it really easy to set up a test where you can seed some data, run the View, compare the expected results, and then it will automatically rollback the data that you just seeded for the test. And it is very easy to update as you add more fields to the View. AND it requires no additional objects in your DB like some other SQL "unit" testing suites.
You can find more info on using DbFit at:
http://benilovj.github.com/dbfit
http://groups.google.com/group/dbfit
And here is a tutorial that I wrote for it that explains the basic options:
http://www.sqlservercentral.com/articles/Testing/64636/
This is a very difficult question to answer. It almost sounds to me like You want to make a single test that tests all in one go.
First, Your app should be constructed, so each functionality is isolated in its own class, thereby making it easy to test AND easy to replace by stubs when testing other things. Dependencies on other functions should be injected (Dependency Injection).
Second, you should use the same technique for external systems like database connections and SPSS file writers. This involves wrapping such functionality so these dependencies also can be injected, and thus replaced by stubs when testing other aspects of your app.
Third, be aware that if tests are hard to write, 99,99% of the time this indicates that your design is not as strong as it could be.
Regards,
Morten
I want to write unit tests with NUnit that hit the database. I'd like to have the database in a consistent state for each test. I thought transactions would allow me to "undo" each test so I searched around and found several articles from 2004-05 on the topic:
http://weblogs.asp.net/rosherove/archive/2004/07/12/180189.aspx
http://weblogs.asp.net/rosherove/archive/2004/10/05/238201.aspx
http://davidhayden.com/blog/dave/archive/2004/07/12/365.aspx
http://haacked.com/archive/2005/12/28/11377.aspx
These seem to resolve around implementing a custom attribute for NUnit which builds in the ability to rollback DB operations after each test executes.
That's great but...
Does this functionality exists somewhere in NUnit natively?
Has this technique been improved upon in the last 4 years?
Is this still the best way to test database-related code?
Edit: it's not that I want to test my DAL specifically, it's more that I want to test pieces of my code that interact with the database. For these tests to be "no-touch" and repeatable, it'd be awesome if I could reset the database after each one.
Further, I want to ease this into an existing project that has no testing place at the moment. For that reason, I can't practically script up a database and data from scratch for each test.
NUnit now has a [Rollback] attribute, but I prefer to do it a different way. I use the TransactionScope class. There are a couple of ways to use it.
[Test]
public void YourTest()
{
using (TransactionScope scope = new TransactionScope())
{
// your test code here
}
}
Since you didn't tell the TransactionScope to commit it will rollback automatically. It works even if an assertion fails or some other exception is thrown.
The other way is to use the [SetUp] to create the TransactionScope and [TearDown] to call Dispose on it. It cuts out some code duplication, but accomplishes the same thing.
[TestFixture]
public class YourFixture
{
private TransactionScope scope;
[SetUp]
public void SetUp()
{
scope = new TransactionScope();
}
[TearDown]
public void TearDown()
{
scope.Dispose();
}
[Test]
public void YourTest()
{
// your test code here
}
}
This is as safe as the using statement in an individual test because NUnit will guarantee that TearDown is called.
Having said all that I do think that tests that hit the database are not really unit tests. I still write them, but I think of them as integration tests. I still see them as providing value. One place I use them often is in testing LINQ to SQL code. I don't use the designer. I hand write the DTO's and attributes. I've been known to get it wrong. The integration tests help catch my mistake.
I just went to a .NET user group and the presenter said he used SQLlite in test setup and teardown and used the in memory option. He had to fudge the connection a little and explicit destroy the connection, but it would give a clean DB every time.
http://houseofbilz.com/archive/2008/11/14/update-for-the-activerecord-quotmockquot-framework.aspx
I would call these integration tests, but no matter. What I have done for such tests is have my setup methods in the test class clear all the tables of interest before each test. I generally hand write the SQL to do this so that I'm not using the classes under test.
Generally, I rely on an ORM for my datalayer and thus I don't write unit tests for much there. I don't feel a need to unit test code that I don't write. For code that I add in the layer, I generally use dependency injection to abstract out the actual connection to the database so that when I test my code, it doesn't touch the actual database. Do this in conjunction with a mocking framework for best results.
For this sort of testing, I experimented with NDbUnit (working in concert with NUnit). If memory serves, it was a port of DbUnit from the Java platform. It had a lot of slick commands for just the sort of thing you're trying to do. The project appears to have moved here:
http://code.google.com/p/ndbunit/
(it used to be at http://ndbunit.org).
The source appears to be available via this link:
http://ndbunit.googlecode.com/svn/trunk/
Consider creating a database script so that you can run it automatically from NUnit as well as manually for other types of testing. For example, if using Oracle then kick off SqlPlus from within NUnit and run the scripts. These scripts are usually faster to write and easier to read. Also, very importantly, running SQL from Toad or equivalent is more illuminating than running SQL from code or going through an ORM from code. Generally I'll create both a setup and teardown script and put them in setup and teardown methods.
Whether you should be going through the DB at all from unit tests is another discussion. I believe it often does make sense to do so. For many apps the database is the absolute center of action, the logic is highly set based, and all the other technologies and languages and techniques are passing ghosts. And with the rise of functional languages we are starting to realize that SQL, like JavaScript, is actually a great language that was right there under our noses all these years.
Just as an aside, Linq to SQL (which I like in concept though have never used) almost seems to me like a way to do raw SQL from within code without admitting what we are doing. Some people like SQL and know they like it, others like it and don't know they like it. :)
For anyone coming to this thread these days like me, I'd like to recommend trying the Reseed library I'm developing currently for this specific case.
Neither in-memory db replacement (lack of features) nor transaction rollback (transactions can't be nested) were a suitable option for me, so I ended up with a simple delete/insert cycle for the data restore purpose. Ended up with a library to generate those, while trying to optimize my tests speed and simplicity of setup. Would be happy if it helps anyone else.
Another alternative I'd recommend is using database snapshots to restore data, which is of comparable performance and usability.
Workflow is as follows:
delete existing snapshots;
create db;
insert data;
create snapshot ;
execute test;
restore from snapshot;
go to "execute test" until none left;
drop snapshot.
It's suitable if you could have the only data script for all the tests and allows you to execute the insertion (which is supposed to be the slowest) the only time, moreover you don't need data cleanup script at all.
For further performance improvement, as such tests could take a lot of time, consider using a pool of databases and tests parallelization.