Below is the piece of the code of my action :-
public ActionResult Edit(int id)
{
ProductViewModel viewmodel = GetProduct(id);
if (viewmodel != null)
{
....................
}
}
In above code the if condition is based on the viewmodel.Which is returning from the GetProduct() method.Where GetProduct() method is the private method of the controller.
And i want to mock the ProductViewModel in my unit test method with MOQ.Can anyone suggest me what is the best way to do that ?
Ideally your viewModel should only have public properties that your view will be bound to. So there should not be a scenario where you would need to mock the viewModel class.
If it is possible to, mock the GetProduct method to return an instance of ProductViewModel where the public properties have already been set. That way your viewModel will return exactly the values you want it to return for your test case.
Usually using the MVVM pattern will look like :
public class MainViewModel : MyViewModelBase
{
private readonly IDataService _dataService;
public MainViewModel(IDataService dataService)
{
_dataService = dataService;
// ...
}
//..
}
And you'll have a locator that looks like:
public class ViewModelLocator
{
static ViewModelLocator()
{
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
if (ViewModelBase.IsInDesignModeStatic)
{
SimpleIoc.Default.Register<IDataService, Design.DesignDataService>();
}
else
{
SimpleIoc.Default.Register<IDataService, DataService>();
}
// Here you'll register your view models
SimpleIoc.Default.Register<MainViewModel>();
}
//..
}
So, mocking this is fairly easy, just use the DI to pass in whatever you want to pass, and hook your methods either to static data (usually done to have nice output in design mode), or dummy methods that will return whatever it is you need.
The correct approach is to test indirectly the GetProduct method. Based on the name you are getting info from some kind of storage and you can mock that storage and return an object which is mapped by GetProduct in the ViewModel you want. You shouldn't mock method of the same class you are testing.
Your controller is very strongly coupled with the business logic, in this case the GetProduct method. I would suggest to restructure your code to have an interface for your "Product" specific business logic. The product controller should depend on an abstraction i.e. the interface and not anything that is concrete.
Use any dependency injection framework like sring.net, MS unity etc to inject concrete implementations (dependencies) into your controller.
Now use MOQ to mock the business logic so that controller can be tested in isolation.
Lastly, this is just another wonderful example demonstrating how if it becomes difficult to unit test a particular code component, it more than often points towards a design flaw than a unit testing/mocking framework incapability.
Related
So I have created the simplest of the applications using ASP.NET MVC (in .NET Framework) and I want to demo dependency injection to a junior using this. it is very simple code, even a newbie can understand it.
public interface IMovieRepository
{
MyViewModel GetDetails(string movie);
}
public class MoviesController : Controller
{
[HttpPost]
public async Task<ActionResult> Search(string movie)
{
// Confusion here! Is the below line a good place to inject dependency
IMovieRepository repository = new DBMovieRepository(); // <-- it can be DBMovieRepository or WebServiceMovieRepository or MockMovieRepository
MovieFinder finder = new MovieFinder(repository);
MyViewModel model = await finder.Find(movie);
return View(model);
}
}
public class MovieFinder
{
private IMovieRepository _repository;
public MovieFinder(IMovieRepository repository)
{
_repository = repository;
}
public async Task<MyViewModel> Find(string movie)
{
// Connect to database and return a detailed object
var myViewModelObj = _repository.GetDetails(movie);
return myViewModelObj;
}
}
public class DBMovieRepository : IMovieRepository
{
public MyViewModel GetDetails()
{
// Code for fetching data from a database
}
}
public class WebServiceMovieRepository : IMovieRepository
{
public MyViewModel GetDetails()
{
// Code for fetching data from a IMDB webservice
}
}
public class MockMovieRepository : IMovieRepository
{
public MyViewModel GetDetails()
{
// Code for returning a mock object here
}
}
There is an inline comment in the code where I asked that my confusion is here. Is that a good place to inject dependencies or do I have to inject it in the MoviesController constructor. If yes, then how will I pass it to the constructor? This is a .NET Framework 4.5 application and I don't want to complicate the lesson by introducing a DI Container and just want to use Pure DI to clarify the concept to my junior.
This is a .NET Framework 4.5 application and I don't want to complicate the lesson by introducing a DI Container and just want to use Pure DI to clarify the concept to my junior.
That literally doesn't make sense.
Pure DI
Or Dependency Injection simply means using IOC to provide an Instance of a Dependency to the object (via Constructor or Property).
Inversion of Control simply means that instead of the dependent object creating the Dependency, you invert control to something else to provide the instance.
You can Architect your Controller to use IOC. You can't DI without something providing the instance. The most lightweight/semi-hacky way to write your DI with minimum effort using your stack is to write your own Controller Factory to inspect your constructor for its dependencies and inject whatever those dependencies are (or just assume what it needs, pass it... yikes).
Relevant SO Question of Mine: My MVC Custom ControllerFactory works but could it be better?
I have an application that is written using c# on the top of asp.net MVC 5. I created a separate repository for each model in my app by implementing the following interface.
public interface IRepository<TModel>
where TModel : class
{
TModel Get(int id);
IEnumerable<TModel> GetAll();
IQueryable<TModel> Find(Expression<Func<TModel, bool>> predicate);
TModel SingleOrDefault(Expression<Func<TModel, bool>> predicate);
TModel Add(TModel entity);
IEnumerable<TModel> AddRange(IEnumerable<TModel> entities);
void Remove(TModel entity);
void RemoveRange(IEnumerable<TModel> entities);
void Update(TModel entity);
}
Although, I saw many implementation where each repository implement a Save method, i did not. I didn’t think it is a good practice where each repository save separately. Which is why I implemented a unit-of-work so that all of my repositories work as a cohesive unit. In my mind it should be the unit-of-work responsibility to handle the saving which enables transactions and the ability to rollback or commit changes when needed.
When I implemented the repository pattern, I felt it would be a good idea to extend each repository as needed where I can have custom IQueryable object returned by the repository to reuse query logic and simple call that from my controller or other places like view helpers. So I could do something like this in my repository directly
public IQueryAble<Car> GetCarsByMakerId(int makerId)
{
// I have typically would have more logic here, but I stripped it out for simplicity.
Return DbContext.Cars.Where(x => x.MakerId == makerId);
}
Then I came to realize that in some cases, I need to write some logic which requires other repositories to handle the business needs.
I came to realize that extending each repository logic with logic other than CRUD operation may not be a good idea.
Instead, it sounds like I should add a service provider for each of my repositories where the service provider providers a method to wrap the business logic/rules.
Using the above example, I would create a CarServiceProvider which accepts an instance of the unit-of-work. Then the service provider will utilize the injected unit-of-work to handle the business need which will allow me to reuse my business logic and separate that out of my repositories. Thus, limiting the repositories to only CRUD operation along with a new method I called it Query() which enables me to create a query.
However, the issue with adding a service provider for each repositories means I have to inject a lot more classes into my controller’s constructor. So my controller constructor my need to look something like this
public class CarController
{
public CarController(IUnitOfWork unitOfWork, Ilog log, ICarServiceProvider car, ICarColorService color, ICarMakerService maker, ICarMakerService carMakerService, ICarSellerService seller, IUserServiceProvider user)
{
_unitOfWork = unitOfWork;
_log = log;
_customer = customer;
_user = user;
_car = car;
_carColor = color;
_carMaker = maker;
_seller = seller;
}
public ActionResult Index()
{
}
public ActionResult Create()
{
var viewModel = new CreateCarViewModel();
// This will need to set the car colors, car maker, car sizes....
viewModel.CreateForm(_carColor, _carMaker, _seller);
return View(viewModel);
}
[HttpPost]
public ActionResult Create(CreateCarViewModel viewModel)
{
if(ModelState.IsValid)
{
using(var batch = new _unitOfWork.StartBatch())
{
try
{
var car = _car.AddNewCar(viewModel, _user.Id);
var sellers = car.AddSellers(viewModel.SellerIds);
batch.Commit();
return RedirectAction("Index");
}
catch (Exception e)
{
batch.rollback();
ModelState.AddModelError(string.Empty, e.Message);
_log.AddError(e.Message);
}
}
}
// At this point we know something went wrong, so we need to create the dropdown menus before we can render the view
// This will need to set the car colors, car maker, car sizes....
viewModel.CreateForm(_carColor, _carMaker, _seller);
return View(viewModel);
}
}
As you can see now I am stuffing all these dependencies into my constructor to be able to use them which sounds like a new problem I have to work with or solve. The good news that I am using an IoC container which resolves all these dependencies for me. But the fact that I have all these dependencies in the constructor is bothering me.
My questions are
Is it a good idea to take all of my custom logic out of the repositories and extract that into a separate service provider classes?
Is injecting these services as needed one at a time is the way to go? Is there a better approach to make this process easy by creating a container for all of my services classes where I would inject one dependency instead of 3+?
Look into refactoring...read this http://blog.ploeh.dk/2010/02/02/RefactoringtoAggregateServices/
Hi I am just writting my first unit test and I have a case where I have to test if the correct mapper is returned.
This is my code:
public UserPersonalDetailsDTO GetUserPersonalDetails(int personId)
{
var mapper = ServiceLocator.GetInstance<IMappingService<UserPersonalDetails, UserPersonalDetailsDTO>>();
var userPersonalDetails = UnitOfWork.PersonData.GetUserPersonalDetails(personId);
var userPersonalDetailsDTO = mapper.Map(userPersonalDetails);
return userPersonalDetailsDTO;
}
How would I test if I am getting the correct mapper?
EDIT
I forgot to mention that I am using Unity as my DI Framework this si my constructor:
public ProfileService(IEConnectUow uow, IValidationService validationService, IServiceLocator serviceLocator)
: base(uow, serviceLocator)
{
m_ValidationService = validationService;
}
My CUrrent class inherits from a BaseCLass that have this properties:
protected IEConnectUow UnitOfWork { get; set; }
protected IServiceLocator ServiceLocator { get; set; }
public BaseService(IEConnectUow uow, IServiceLocator serviceLocator)
{
UnitOfWork = uow;
ServiceLocator = serviceLocator;
}
That code is really difficult to unit test. At least two of the dependencies come in via statics (ServiceLocator, UnitOfWork).
I would refactor the code to the following
public class Whatever {
private IMappingService<UserPersonDetails, UserPersonalDetailsDTO> mapper;
private PersonData personData;
public Whatever(IMappingService<UserPersonDetails, UserPersonalDetailsDTO> mapper,
PersonData personData) {}
public UserPersonalDetailsDTO GetUserPersonalDetails(int personId) {
var userPersonalDetails = personData.GetUserPersonalDetails(personId);
var userPersonalDetailsDTO = mapper.Map(userPersonalDetails);
return userPersonalDetailsDTO;
}
}
In the whatever class you can now test the interactions with the objects you pass in. You don't want to be testing that the right mapper is returned in this class. In a unit test, ideally you only want to test the logic of the class and its interactions with dependencies. In this case, I'd simply test the interactions. GetUserPersonalDetails talks to the PersonData object, and uses the Mapper to get the result.
Testing that you get the right mapper isn't the responsibility of this class. Factor that logic out somewhere (perhaps starting with ServiceLocator) into its own class with its own dependencies and verify it does what you want.
Your ServiceLocator is some factory class. If the ServiceLocator is writen by you, you can test is seperately. If it is a libary class, the libary is tested (assumue). You can test is the GetInstance<IMappingService<UserPersonalDetails, UserPersonalDetailsDTO>>(); method is called for the correct types. This can be done with a mocking framework. You make a mock for the GetInstance method and then check if it is called, you know the GetInstance method is right because you have tested it somewhere else.
My test whould look like (pseudo code):
Make mock ServiceLocator.GetInstance
Make mock UnitOfWork.PersonData.GetUserPersonalDetails
Make mock mapper.Map
call GetUserPersonalDetails(int personId)
check if ServiceLocator.GetInstance was correct
In an MVC3 application, I need to construct a domain object from values contained in the incoming Http Request. The logic is sufficiently complex that I have created a factory class with the responsibility of creating my domain object.
My question is whether to pass into this factory class the value of the Controller's Request property, or should I reference the value of the static HttpContext.Request property from inside the factory class?
My intention is to unit test both the controller and the factory class so I will have perform the necessary overhead of setting up the HttpContext somewhere. I just wondered if there are any general rules to stick to?
Simply pass a NameValueCollection to your factory class:
public SomeDomainObject ConstructDomainObject(NameValueCollection data)
{
...
}
and then in your controller simply:
var domainModel = factory.ConstructDomainObject(Request.Params);
Now you can unit test the ConstructDomainObject method as much as you like.
If you want to test your controller in isolation then make have this factory object implement an interface:
public interface IMyFactory
{
SomeDomainObject ConstructDomainObject(NameValueCollection data);
}
that your controller will work with:
public class SomeController: Controller
{
private readonly IMyFactory factory;
public SomeController(IMyFactory factory)
{
this.factory = factory;
}
public ActionResult SomeAction()
{
var domainModel = this.factory.ConstructDomainObject(Request.Params);
...
}
}
All this being said, have you considered writing a custom model binder? In ASP.NET MVC the responsibility of the model binder is exactly that: instantiate some model from the request. This way you don't need to be reinventing some wheels but you will be using what's natively built into the framework for this purpose.
I have a legacy code, and I have a problem with reconstructor it.
At start of my application I load from WCF to property on App (this is SL application) list of users.
Then every control (for sending emails, view calendar and assigning tasks) use this property as
(App.Current as App).Users
Now, I'm trying to create Unit Test for one of controls that use this lists, and I'm stuck.
Should I make a Constructor Injection(I'm using Unity) with App as parameter? Or maybe introduce some class to hold this list?
Updated with OP's implementation as the pseudocode was incomplete.
I propose create an interface for all your application services
Inject IApplicationService to your modules.
You can use this interface for all the services the application provides(probably you will need more). Mock the interface for the unit tests
OP's implemantation
public interface IApplicationService
{
List<User> Users{get;set;}
}
public class ApplicationService : IApplicationService
{
public List<User> Users
{
get { return (App.Current as App).Users; }
set { (App.Current as App).Users = value; }
}
}
public partial class MainWindow : UserControl
{
readonly IApplicationService _applicationService
public MainWindow(IApplicationService applicationService)
{
_applicationService=applicationService;
}
}
I would create a wrapper class that will expose the list of users. In production code this class will just be a wrapper around your App.Current property and it can be injected in the constructor trough Unity.
In your Unit Tests you can easily mock the App parameter and pass it when constructing a new SUT.
Something like:
public interface IUserList
{
List<User> Users { get; }
}
public class SUT
{
private IUserList UserList { get; set; }
public SUT(IUserList userList)
{
this.UserList = userList;
}
}
public class AppUserList : IUserList
{
public List<User> Users
{
get
{
return ((App)App.Current).Users;
}
}
}
For Silverlight there is an extension model called Application Extension Services.
For infrastructure purposes that might be a better alternative than adding properties to your app class and casting App.Currentback and forth.
Downside of that model is the creation of a singleton you would have to initialize for your unit tests. It would also hide the dependency on Users in your consuming classes.
Your users seem to be just data. Making that data an ambient context which can be accessed and edited everywhere in your application will bite you. You don't know who does what with that data and when he does it. This is like a session state.
So making the dependency on your data explicit would be a first step to be able to track abuse of that data.
If it makes sense to you to create a "data holder object" that has a property for Users or directly inject that data into your consumers is up to you. If there is more data than just Usersit is tempting to put all of them into the same central data store object, even if your specific consumers don't need them.
Jimmy's answer is great, but can be provide quite a bit, and some errors fixed. Differences are explained at the bottom below the code/instructions:
Create a public interface: IUserService
public interface IUserService
{
// Implemented functionality as methods where possible for better
// extendability (like IoC)
IEnumerable<User> Users();
// Add any other user service stuff as you see fit.
void AddUser(User user);
}
Write a UserService that implements IUserService
public class UserService : IUserService
{
// If you need DI for this service, follow the same pattern of using
// fields and controller injection. I left examples in comment below.
// private readonly IRepository _repository;
// Constructor is unnecessary if you do not need DI example.
public UserService(/* IRepository repository */)
{
// _repository = repository;
}
// Methods
public IEnumerable<User> Users()
{
return ((App)App.Current).Users;
}
public void AddUser(User user)
{
((App)App.Current).Users.Add(user);
}
}
Inject IUserService into classes via their Constructor
In this case your MainWindow as an example:
public partial class MainWindow : UserControl
{
private readonly IUserService _userService;
public MainWindow(IUserService userService)
{
_userService = userService;
}
// Example method consuming the service
public IEnumerable<User> GetUsers()
{
return _userService.Users();
}
}
Differences:
Separate your User Services from a central Application Service
Better modularity. In addition I use an IApplicationService for more central/global data like Api Keys, Timeouts, cleanup, DB prepping, etc.
Return IEnumerable<T> instead of List<T>
This is just a golden rule of thumb for keeping things dry and not imposing hard instantiations on your consuming classes. Refactoring is easier/safer, and your code more extensible.
Use methods instead of properties
This is preference, but I think it smart in a service layer to use methods where possible so that you can introduce filters and overloads or continue to use dependency injection - for example, you could add GetUsers(string lastName), GetUsers(string lastName, string firstName) and maintain a clean interface for your consuming classes.
Cast App.Current without the as keyword
This is a good practice because using the as keyword means when the cast fails it will return null, rather than throw an exception. I prefer the exception because 99% of the time, if your cast fails, your next operations will too. :)
Enjoy!