I want to mock the below line of code(by MOQ in C#,MVC) :-
CustomerDto target = CustomerService.GetAllCustomer().FirstOrDefault(n => n.CustomerID == customer.CustomerID);
Where CustomerService.GetAllCustomer() function is the dependency in the controller method.
Where it is using FirstOrDefault() function.And in unit testing i have no clue how to mock it.
Can any one suggest me way for it ?
Mock(stub) your dependency only. In this case it is CustomerService, which should be some interface or abstract class implementation.
Make your GetAllCustomer method return some fake customers.
FirstOrDefault is a .NET Framework method which should not be tested (it is already tested by the framework developers)
IMO, you need to start decoupling your code by moving towards a more layered approach. I am not quite sure what you need to achieve by mocking the FirstOrDefault method. I suggest having three layers and their tests as below -
Data access - uses EF and its DB context and implements a data access interface. You should unit test this without mocking EF's db context. Tests for this layer would be "state" dependent. By that I mean, your tests will work with real data and database for the CRUD operations. You just need to make sure you do not persist the changes to the db after the test run. One can use Spring.Net's testing library to achieve this or simply run your tests under a transaction scope and roll back the transaction after every test run (in the clean up).
Business logic - contains the business logic and works with the data access interface. Use any DI framework like spring.net or ms unity to inject the data access layer. You should unit test this by trying to avoid actual database calls. This is where something like a NMock, Rhinomock or MOQ comes into picture. Set up boundary and exception conditions using mocks and make sure your business logic addresses all the concerns.
MVC Controller - Will delegate the calls to business logic layer and most probably handle stuff like notifications etc needed on the UI. It should be a judgement call if the controller really needs to be unit tested. It could be an overkill more than often. I would rather suggest considering automated UI test cases using something like selenium or Microsoft's coded UI tests.
Related
Sorry if I am asking very basic question,
I have set of web services (developed using .Net WebApi). These services are either business layer or data access layer APIs. These APIs are either dependent on other services or database itself.
I want to write unit test cases for it. I have following questions
As business layer APIs has dependency on data access service or some other service. If I write unit test just to invoke business API then it would invoke data access API. Is this the correct way to write unit test case? or should I inject all dependency object with unit test? I think earlier one would be integration test not unit test.
Should I write unit tests for Data access layer at all? I checked this link (Writing tests for data access code: Unit tests are waste) and it says DAL does not require unit tests. Should I still write tests for data access layer. I think it would be integration test not unit tests?
Question 1:
I would say if you want to do TDD, then it's not the "correct" way, because as you said, you would be performing integration tests. Then again, maybe you don't want to do TDD and integration tests are good enough for you, but to answer the question: this wouldn't be the proper way to **unit-**test your code.
Question 2
I would say it depends what you have in your data access layer. For instance, if you implement repositories, you will probably want to write a few tests.
Save method
You want to make sure that given an entity that you have retrieved from your repository, editing some properties of this entity and persisting the changes will actually save the modifications and not create a new entity. Now: you might think this is an integration test, but it really depends on how well designed your code is. For instance, your repository could be just an extra layer of logic on top of a low-level ORM. In that case, when testing the save method, what you will do is that you will assert that the right methods are called with the right parameters on the ORM service injected in your repository.
Errors and exceptions
While accessing data, it is possible to have problems such as connection to the database being broken, or that the format of the data is not as expected, or deserialization problems. If you want to provide some good error handling and perhaps create custom exceptions and add more information to them depending on the context, then you definitely want to write tests to make sure the corrext information is propagated
on the other hand
If your DAL is just a few classes that wrap a non-mockable ORM, and you don't have any logic in there, then perhaps you don't need tests, but it seems that this doesn't happen too often, you will pretty much always have a bit of logic that can go wrong and that you want to test.
In an MVC4 C# website, we are using Unit Testing to test our code. What we are currently doing is creating a mock database, then testing each layer:
Test the Database - connecting, initializing, load, etc.
Test the code accessing the database
Test the view layer
I want these three categories to be run in order and only if the previous one passed. Is this the right way to go about it? The old way we were doing it was using a Dependency Injection framework was a weird approach to mock testing. We actually created a mock class for each data accessor, which sucks because we have to re implement the logic of each method, and it didn't really add any value because if we made a mistake with the logic the first time, we'll make it a second.
I want these three categories to be run in order and only if the
previous one passed. Is this the right way to go about it?
No. You should be test everything in isolation and because of that any failing data access code should be completely unrelated to the view. So the view unit tests should fail for a completely different reason and because of that you should always run all tests.
In general, tests should run in isolation, and should not depend on any other tests. It seems to me that the view layer still depends on the data access code, but that you only abstracted the layer below. In that case, from the view's perspective, you are mocking an indirect dependency, which makes your unit tests more complex than strictly needed.
The old way we were doing it was using a Dependency Injection
framework was a weird approach to mock testing
I'm not sure if I get this, but it seems as if you were using the DI container inside your unit tests. This is a absolute no-no. Don't clutter your tests with any DI framework. And there's no need to. Just design your classes around the dependency injection principle (expose all dependencies as constructor arguments) and in your test you just manually new up the class under test with fake dependencies -or- when this leads to repetitive code, create a factory method in your test class that creates a new instance of the class under test.
We actually created a mock class for each data accessor, which sucks
I'm not sure, but it sounds as if there's something wrong with your design here. You would normally have a IRepository<T> interface for which you would have multiple implementations, such as a UserRepository : IRepository<User>, and OrderRepository : IRepository<Order>. In your test suite, you will have one generic FakeRespository<T> or InMemoryRepository<T> and you're done. No need to mock many classes here.
Here are two great books you should definitely read:
The Art of Unit Testing
Dependency Injection in .NET
Those books will change your life. And since you'll be reading anyway, do read this book as well (not related to your question, but code be a life changer as well).
I am just wondering if there a way I can unit test some of my controller Action in
MVC without using Repository pattern. I have develop an ASP.NET MVC site but did this without unit testing at the initial stage. Now I want to demonstrate some unit test to my tutor using may be two or more action in my controller. Most of my actions logic get data from database and one controller get data from different tables i.e actions in one controller read from different table. which I think that can be test using Generic Repository pattern. As a beginner I found that I can only unit test a code that is not coming from database but unfortunately most of the code in my controller Actions come from database. i am using the default test tool in visual Studio and EF code first approach for my database.
for example i will like to unit test only the below Actions without having to unit test other action that are in the same controller.
public ActionResult Index()
{
var model = _db.PhotoGallery;
return View(model);
}
This is just for demonstration purpose.
By definition, a unit test should only affect the method that it calls. If you can find a way to mock your _db object so that you're not actually causing a database round-trip, then you can unit test this method that relies on it. Otherwise, no.
Is your _db field's type an interface? Is it being provided via injection? If so, it's likely that you can unit test this method.
Without removing the direct dependency to the database in you controller methods you will not be able to unit test these methods.
The overall recommended way of doing this would be using an IOC Container (e.g. Ninject) in combination with MVC that allows you to pass the data you need to the constructor of your controller. That "data object" must not be tied to the database, typically it is either just a POCO object or passed as an interface.
In your unit tests you can then substitute these dependencies using an in-memory data object constructed just for your unit tests, typically "mocked" using a mocking framework (e.g. Rhino Mocks or Moq).
Using this approach you not only make your controllers unit-testable but also will end up with very loosely coupled code, a benefit that might pay off for later development.
That's what called testable code :)
When you perform unit testing, you need to be sure, that only reason of failing test is changing in SUT (system under test, or class being tested) implementation. Of course, it could be broken when dependency API changes (thats OK, you should modify SUT to use new API), but it never should fail if dependency implementations changed. Thats why mocking and stubbing used.
But if you want to mock dependency, you should not create it inside SUT. It should be injected into SUT (constructor, property of parameter injection).
So, back to your case:
if you want to have testable class, you have to inject dependency (db)
dependency should be mocked
you not forced to use Repository pattern. If you can mock your db class, just mock it. Or use any other data access abstraction
I've got NHibernate-based (constructor ISessionFactory injection) generic repository implementation which is stored inside DAL. It implements contract which is stored in `Domain Layer'.
Should I test real repository behavior using SQl CE or should I refactor my application to support agnostic-like (like in Tim Maccharty's book http://www.wrox.com/WileyCDA/WroxTitle/productCd-0470147563,descCd-authorInfo.html) Unit of Work and then give my fake implementation of IUnitOfWorkRepository?
Is it a valid approach to run tests on a local database exposing real repository implementation?
Thanks!
The issue is what your are testing and why. That will answer the question.
If:
I want to test a third party tool
That is, are you testing if NHibernate is working (not a kind of test
I do). Then do whatever it requires, so refactoring not required. Loose yourself.
I want to test how my code interacts with a thrid party tool
Then you are talking about what I like to call a interaction test. Refactoring is required as your more interested in how your using NHiberate than if it works.
I want to test my code
The abstract NHibernate entirely. Do whatever is necessary ... wrapper? Your now back into unit testing.
I want to test my application from a user point of view
I think this is above the scope your talking. But you can use this scope talking about components. So ... hmmm ... worthwhile but not easy. Not a unit test, so you want to instantiate the component/app and run the whole thing as its 'user' does. I call these 'UATs' and usually implement as 'Coded UATs'.
A unit test is testing a unit in isolation. So, no, it's not even a unit test if you're going to the database.
Abstract away and test your repositories with mocked up interfaces.
I think to test the repositories you need to use the actual scenario. Otherwise you don't have any other place to test the database access. Mocking the repositories is not a good practice. Because you don't have any logic which is need to test in the repositories. I think you need to write integration tests which is calling actual repositories to have any benefit from it.
My question may appear really stupid for some of you but i have to ask.. Sorry..
I don't really understand principles of unit testing.. How can you test classes of your business classes or Data access layer without modify your database?
I explain, i have a functionality who update a field in a database.. Nothing so amazing..
The Business layer class is instantiated and the method BLL.Update() makes some controls and finally instantiate a DAL class who launch a stored procedure in the database with the correct parameters.
Its works but my question is..
To do unit tests who test the DALayer class i have to impact the database in the tests! To test for example if the value 5 is well passed to the DataBase i have to do that and database's field will be 5 after the test!
So i know normally the system is not impacted by tests so i don't understand how you can do tests without without execute methods..
Tx for answers and excuse my poor English..
I will divide your question into several sub questions because it is hard to answer them together.
Unit testing x Integration testing
When you write unit test you are testing simple unit. That means you are testing single execution path in tested method. You need to avoid testing its dependencies like mentioned database. You usually write simple unit test for each execution path so that you have good code coverage by your tests.
When you write integration test you are testing all layers to see if integration and configuration works. You usually don't write integration test for each execution path because there is to many combination accross all layers.
Testing business classes - unit testing
You need to test your business classes without dependency to DAL and DB. To do that you have to design your BL class so that those dependencies are injected from outside. First you need to define abstract class or interface for DAL and pass that DAL interface as parameter to constructor (another way is to expose setable property on BL class). When you test your BL class you will use another implementation of DAL interface which is not dependent on DB. There are well known test patterns Mock, Stub and Fake which defines how to create and use those dummy implementations. Mocking is also supported by many testing frameworks.
Testing data access layer - integration testing
You need to test your DAL against real DB. You will prepare testing DB with test set of data and you will write your tests to work with that data. Each test will run in its own transaction which will be rolled back at the end so it will not modify initial data set.
Best regards, Ladislav
For the scenario you describe in terms of db interaction, mocking is useful. If you have a chance, take a look at Rhino Mocks
You use Inversion of Control together with a mocking framework, e.g. Rhino Mocks as someone already mentioned
If you are not resorting to mocking and using actual DB in testing then it will be integration testing in layman terms and it's not a unit test anymore. I worked on a project where a dedicated sql .mdf was in source control that was attached to database server using NUnit in [Setup] part of [SetupFixture], similary detached in [TearDown]. This was done everytime NUnit test were performed and could be very time consuming depending upon the SQL code you have as well as size of data can make worse.
Now the catch is the maintenance overhead, you may change the DB scehma during you sprint cycle and at relaease, the change DB script has to be run on all databases used in your development and testing including the one used for integration testing as mentioned above. Not just that, new test data (as someone mentioned above) has to be popoulated for new tables/columns created and likewise, the exisitng data may need to be cleansed as well owing to requirements changes or bug fixes.
This seems to be a task in itself and someone competent in team can take the ownership or if time permits you can integrate the execution of change scripts as part of Continuous Integration if you already implemented one. Still the adding and cleansing the test data need to be taken care of manually.