I am working on this WebAPI project and I need to create unit tests for it. The base of the project was created using VS 2010 , and then an WebApi Module was added.
The workings of the controller are kinda getting in the way of testing/mocking. I am using xUnit and Moq , but there is absolutely no need to stick with those two.
The application uses specific objects to deal with database access, so I have the
controllerObject and its contructor requires the DataAccessObject
I am having problem with mocking the controller / dataaccess pair. The first test i´m trying to run is a GetAllFromDataBase, but i dont really have a clue on how to do it.
EDIT:
I did what Cuong Le told me and the whole is moving now, i really apreciate it. But i stumped into another problem. To access the API, there is a username/password pair and my controller uses Thread.CurrentPrincipal.Identity.Name; right now i would need to set this value for it to fully work I guess.
Also the valueServiceMock.Setup(service => service.GetValues())
.Returns(new[] { "value1", "value2" });
does not seem to be working. as the code tries to reach for the database, and gets nothing since it cant get a valid username to look for
In order to get your app testable, you need to design for testability in mind.Technically, to design to testability, your app should be loose coupling as much as possible between layers, between components and even between classes.
A lot of hints to design for testability: avoid sealed, static class... But the most popular thing you need to be aware of is dependency injection pattern, instead of creating object inside contructors or methods of other objects, this object should be injected. With this way we make loose dependency between class and easy for us to fake by mocking framework. Esp, for the objects which depend on external resource: network, file or database.
How to inject object by using dependency injection: that's why IocContainer is the right tool for this, it will inject objects for you automatically. IoC Container which I prefer to use is: Autofac and NInject.
Example in here to inject ValueService into ValuesController:
public class ValuesController : ApiController
{
private readonly IValueService _valueService;
public ValuesController(IValueService valueService)
{
_valueService = valueService;
}
public string[] Get()
{
return _valueService.GetValues();
}
public string Get(int id)
{
return _valueService.GetValue(id);
}
}
And below is the simple code to unit test with Moq:
var valueServiceMock = new Mock<IValueService>();
valueServiceMock.Setup(service => service.GetValues())
.Returns(new[] { "value1", "value2" });
var controller = new ValuesController(valueServiceMock.Object);
var values = controller.Get();
Assert.AreEqual(values.Length, 2);
Assert.AreEqual(values[0], "value1");
Assert.AreEqual(values[1], "value2");
Related
Having something like a string parameter in a constructor makes dependency injection very messy. Think:
public class CurrencyActor
{
public CurrencyActor(string currency, IRepository repository)
{
...
There have been other questions (such as this one) to address this particular problem with dependency injection. Often this is solved by rethinking the design and refactoring.
However, what if it actually makes sense to have multiple versions of an object that are each responsible for different data (e.g. a CurrencyActor for each currency)? This is pretty normal when using an actor model such as Akka .NET, but makes sense even outside that domain.
What is the best way to create these multiple instances using dependency injection while passing in the initial state they need?
Having a dependency in a constructor is not messy, it's very very common. There is nothing wrong with this.
You could create a default props static method on the CurrencyActor that takes in your dependencies:
public static Props CreateProps(string currency, Irepository repo)
{
return Props.Create(() => new CurrrncyActor(currency, repo));
}
Then create as many as you like:
var usCurrency = system.ActorOf(CurrencyActor.CreateProps("US", someRepo), "US");
var swedishCurrency = system.ActorOf(CurrencyActor.CreateProps("SEK", someRepo), "SEK");
[Update]
Regarding the use of DI containers with Akka, this was listed as no. 2 out of the top 7 mistakes people make when using akka.net
https://petabridge.com/blog/top-7-akkadotnet-stumbling-blocks/
Thus it’s considered to be a good practice for actors to manage their own dependencies, rather than delegate that work to a DI framework.
So basically don't do it. And if you must, according to that article, Autofac is the best choice
[Update 2]
If you want to dynamically create new instances of the same Actor but change some initial state, then you could have a Supervisor that is responsible for creating them:
public class MatchesSupervisor : ReceiveActor
{
List<IActorRef> _matches = new List<IActorRef>();
public void MatchesSupervisor()
{
Receive<SomeCommandToStartANewMatch>(msg =>
{
// store the currently active matches somewhere, maybe on a FullTime message they would get removed?
_matches.Add(Context.ActorOf(MatchActor.Create(msg.SomeMatchId)));
}
}
}
In the above example, there is no DI container being used, and if each MatchActor needed something else, like an IRepository, then this would be passed into the MatchesSupervisor when it is created, and subsequently passed to each MatchActor when they are created.
It also kinda depends where the state is coming from, and what the mechanism is for starting a new Match - i've just presumed some other Actor is sending a message.
(I'm typing on an ipad so the above code might not actually compile but hopefully you get the idea, i also left out an implementation of MatchActor, but it would just be an Actor that gets some values passed into its constructor)
Hope this helps!
I'm relatively new to unit testing, and brand new to Moq. I have been tasked with writing up some unit tests for some pre-existing code.
I am struggling with the following method, as it makes a call to model.importing.RunJob, which as the name suggests, kicks off a job.
Obviously, I don't want it to actually DO the job, I just want to know that it's called the method.
How would I go about achieving this (ideally avoiding any code changes):
public ActionResult ImportsAndLoads(ImportsAndLoadsViewModel importsAndLoadsModel)
{
Initialise(importsAndLoadsModel);
LoadData(importsAndLoadsModel);
if (importsAndLoadsModel.ActionToPerform == "RunJob")
{
using (var model = new Model())
{
List<Message> lstMessage;
model.importing.RunJob((Jobs)Enum.ToObject(typeof(Jobs), importsAndLoadsModel.SelectedJob), out lstMessage);
importsAndLoadsModel.lstMessages = lstMessage;
}
}
return View(importsAndLoadsModel);
}
As has been discussed in the comments on your question, you can't really test your ImportsAndLoads method in isolation in its current form, using Moq. If you are using a high enough version of Visual Studio, then you may be able to test the method using Shims, however if you're not already using this in your project, it's probably not the right way to go.
As it stands, your code is a little confusing. It's a bit weird having a class called Model, that you're creating, in order to access a property in order to call a RunJob method. If this really is the code, then you might want to encourage the team to revisit the Model class.
One of the suggestions was that you inject your Model dependency instead of creating it (or inject a factory and call out to the factory for creation). This would be the preferable way to go, however it's not a trivial change in approach and really your team needs to buy into it as an approach rather than you making the change as a one-off.
If you aren't using an IOC container already (AutoFac, CastleWindsor, Ninject), then you may want to consider using one. They will make switching to dependency injection easier. If you want to do it by hand, then you can do, but it's harder.
Without knowing about the structure of more of your classes, it's hard to give a complete example, but one approach might be the following:
// Create an importer interface
public interface IImporter {
void RunJob(Jobs job, out List<Message> listMessages);
}
// Implement it in a concrete class
public class Importer : IImporter{
public void RunJob(Jobs job, out List<Message> listMessages) {
// Do whatever it is it does.
}
}
// Modify the constructor of your controller to allow the IImporter
// interface to be injected. Default to null if not supplied, so that
// it can still be crated without parameters by the default MVC plumbing
public class ImportController : Controller
{
private IImporter _importer;
public ImportController(IImporter importer = null) {
// If importer not injected, created a concrete instance
if (null == importer) {
importer = new Importer();
}
// Save dependency for use in actions
_importer = importer;
}
// Use the injected importer in your action, rather than creating a model
public ActionResult ImportsAndLoads(ImportsAndLoadsViewModel importsAndLoadsViewModel)
{
List<Message> listMsgs;
_importer.RunJob(Jobs.One, out listMsgs);
importsAndLoadsViewModel.lstMessages = listMsgs;
return View(importsAndLoadsViewModel);
}
}
This would then allow you to write a test to validate that importsAndLoadsViewModel has been updated as expected, using a test like this:
[Test]
public void TestModelMessagesAreUpdatedFromJobRunner() {
var mockImporter = new Mock<IImporter>();
List<Message> expectedMessages = new List<Message>();
mockImporter.Setup(x=>x.RunJob(It.IsAny<Jobs>(), out expectedMessages));
var model = new ImportsAndLoadsViewModel();
// Inject the mocked importer while constructing your controller
var sut = new ImportController(mockImporter.Object);
// call the action you're testing on your controller
ViewResult response = (ViewResult)sut.ImportsAndLoads(model);
// Validate the the model has been updated to have the messages
// returned by the mocked importer.
Assert.AreEqual(expectedMessages,
((ImportsAndLoadsViewModel)response.Model).lstMessages);
}
This is simplification of what would need to be done / tested to demonstrate an approach. One of the issues to be aware of with injecting dependencies is that it's quite easy to end up creating abstractions of abstractions, pushing the actual logic deeper and deeper into your code, only to find that you've just pushed the problem deeper and that you still don't know how to test a particular piece of logic because in essence it hasn't changed.
I have the basics down of dependency injection but where I'm struggling is trying to put it together properly in an MVC API C# application using Unity. The issue I have is that I will have a controller that has a method, and in that method it will have say two objects. One of these objects will have a dependency on a data access layer and the other doesn't. I'm not quite sure on exactly how to set this up.
Lets say I have a controller with the following method that gets users from a search object. It also uses a SearchParameters object to perform the search. If you search with no name you get all results, or if you put a name you get any users with that name.
public Users[] GetUsers(string name) {
Company.SearchParameters searchParams = new Company.SearchParameters(name);
Company.UserSearchService searchService = new Company.UserSearchService(searchParams);
return searchService.Search();
}
This is of course a super simplified version but in this case UserSearchService in the Search method is doing an explicit database call. So I know that is a dependency I'd have to give it. SearchParameters really is just a class that holds data.
Here is where I'm not sure on exactly what to do next. The Controller itself doesn't have a dependency but since UserSearchService does I'm not sure how using unity I properly set that up and take into account runtime values for the constructor. I'm also not sure if SearchParameters is supposed to be considered a dependency or not.
Additionally SearchParameters and UserSearchService do not have any sort of backing interface if that matters and there are other methods on this controller that interact with other classes that have a similar need of a data access layer dependency such as perhaps Company.UserAccount.
The search parameters shouldn't be part of constructor; it should be part of the "Search" method. The SearchParameter object should not even be known outside of the UserSearchService class (Encapsulation). There should be some refactoring as neleus suggested. At the very least, to get things going, it should be refactored to something similar this:
public Users[] GetUsers(string name) {
// Or however you end up with your UserSearchService object.
// Ideally as an interface and an injected dependency...
Company.UserSearchService searchService = new Company.UserSearchService();
return searchService.Search(name);
}
Company.UserSearchService:
public Users[] Search(string name) {
// A factory would be a better option. This should also be an interface.
Company.SearchParameters searchParams = new Company.SearchParameters(name);
// Your logic here
}
I see here two tasks. The first is a refactoring where static dependencies have to be replaced with interfaces. The second task is to register your stuff in IoC container.
For the first task a minimum you need is to replace all references to Database in your UserSearchService with IDatabase interface (so that it can also be mocked) and allow it to be passed to constructor (constructor injection). To be able to provide an instance of IDatabase to the service you have to create the same dependency for the controller (again constructor injection). Then register the IDatabase implementation as shown in this post.
Update
I agree that dependency has to be removed from the controller. As you #Topojijo have suggested a factory for the UserSearchService can be used in this case. Guessing you have several cervices you need to make a factory for each and there may be an overhead if their count is large. In such case it's better to resolve the service directly from Unity container and move the searchParams to Search method:
public Users[] GetUsers(string name) {
Company.SearchParameters searchParams = new Company.SearchParameters(name);
Company.UserSearchService searchService = container.Resolve<Company.UserSearchService>();
return searchService.Search(searchParams);
}
I'm trying to understand Inversion of Control and how it helps me with my unit testing. I've read several online explanations of IOC and what it does, but I'm just not quite understanding it.
I developed a sample project, which included using StructureMap for unit testing. StructureMap setup code like the following:
private readonly IAccountRepository _accountRepository
public Logon()
{
_accountRepository = ObjectFactory.GetInstance<IAccountRepository>();
}
The thing I'm not understanding though, is as I see it, I could simply declare the above as the following:
AccountRepository _accountRepository = new AccountRepository();
And it would do the same thing as the prior code. So, I was just wondering if someone can help explain to me in a simple way, what the benefit of using IOC is (especially when dealing with unit testing).
Thanks
Inversion of Control is the concept of letting a framework call back into user code. It's a very abstract concept but in essence describes the difference between a library and a framework. IoC can be seen as the "defining characteristic of a framework." We, as program developers, call into libraries, but frameworks instead call into our code; the framework is in control, which is why we say the control is inverted. Any framework supplies hooks that allow us to plug in our code.
Inversion of Control is a pattern that can only be applied by framework developers, or perhaps when you're an application developer interacting with framework code. IoC does not apply when working with application code exclusively, though.
The act of depending on abstractions instead of implementations is called Dependency Inversion, and Dependency Inversion can be practiced by both application and framework developers. What you refer to as IoC is actually Dependency Inversion, and as Krzysztof already commented: what you're doing is not IoC. I'll discuss Dependency Inversion for the remainder of my answer.
There are basically two forms of Dependency Inversion:
Service Locator
Dependency Injection.
Let's start with the Service Locator pattern.
The Service Locator pattern
A Service Locator supplies application components outside the [startup path of your application] with access to an unbounded set of dependencies. As its most implemented, the Service Locator is a Static Factory that can be configured with concrete services before the first consumer begins to use it. (But you’ll equally also find abstract Service Locators.) [source]
Here's an example of a static Service Locator:
public class Service
{
public void SomeOperation()
{
IDependency dependency =
ServiceLocator.GetInstance<IDependency>();
dependency.Execute();
}
}
This example should look familiar to you, because this what you're doing in your Logon method: You are using the Service Locator pattern.
We say that a Service Locator supplies access to an unbounded set of dependencies, because the caller can pass in any type it wishes at runtime. This is opposite to the Dependency Injection pattern.
The Dependency Injection pattern
With the Dependency Injection pattern (DI), you statically declaring a class's required dependencies; typically, by defining them in the constructor. The dependencies are made part of the class's signature. The class itself isn't responsible for getting its dependencies; that responsibility is moved up up the call stack. When refactoring the previous Service class with DI, it would likely become the following:
public class Service
{
private readonly IDependency dependency;
public Service(IDependency dependency)
{
this.dependency = dependency;
}
public void SomeOperation()
{
this.dependency.Execute();
}
}
Comparing both patterns
Both patterns are Dependency Inversion, since in both cases the Service class isn't responsible of creating the dependencies and doesn't know which implementation it is using. It just talks to an abstraction. Both patterns give you flexibility over the implementations a class is using and thus allow you to write more flexible software.
There are, however, many problems with the Service Locator pattern, and that's why it is considered an anti-pattern. You are already experiencing these problems, as you are wondering how Service Locator in your case helps you with unit testing.
The answer is that the Service Locator pattern does not help with unit testing. On the contrary: it makes unit testing harder compared to DI. By letting the class call the ObjectFactory (which is your Service Locator), you create a hard dependency between the two. Replacing IAccountRepository for testing, also means that your unit test must make use of the ObjectFactory. This makes your unit tests harder to read. But more importantly, since the ObjectFactory is a static instance, all unit tests make use of that same instance, which makes it hard to run tests in isolation and swap implementations on a per-test basis.
I used to use a static Service Locator pattern in the past, and the way I dealt with this was by registering dependencies in a Service Locator that I could change on a thread-by-thread basis (using [ThreadStatic] field under the covers). This allowed me to run my tests in parallel (what MSTest does by default) while keeping tests isolated. The problem with this, unfortunately, was that it got complicated really fast, it cluttered the tests with all kind of technical stuff, and it made me spent a lot of time solving these technical problems, while I could have been writing more tests instead.
But even if you use a hybrid solution where you inject an abstract IObjectFactory (an abstract Service Locator) into the constructor of Logon, testing is still more difficult compared to DI because of the implicit relationship between Logon and its dependencies; a test can't immediately see what dependencies are required. On top of that, besides supplying the required dependencies, each test must now supply a correctly configured ObjectFactory to the class.
Conclusion
The real solution to the problems that Service Locator causes is DI. Once you statically declare a class's dependencies in the constructor and inject them from the outside, all those issues are gone. Not only does this make it very clear what dependencies a class needs (no hidden dependencies), but every unit test is itself responsible for injecting the dependencies it needs. This makes writing tests much easier and prevents you from ever having to configure a DI Container in your unit tests.
The idea behind this is to enable you to swap out the default account repository implementation for a more unit testable version. In your unit tests you can now instantiate a version that doesn't make a database call, but instead returns back fixed data. This way you can focus on testing the logic in your methods and free yourself of the dependency to the database.
This is better on many levels:
1) Your tests are more stable since you no longer have to worry about tests failing due to data changes in the database
2) Your tests will run faster since you don't call out to an external data source
3) You can more easily simulate all your test conditions since your mocked repository can return any type of data needed to test any condition
The key to answer your question is testability and if you want to manage the lifetime of the injected objects or if you are going to let the IoC container do it for you.
Let's say for example that you are writing a class that uses your repository and you want to test it.
If you do something like the following:
public class MyClass
{
public MyEntity GetEntityBy(long id)
{
AccountRepository _accountRepository = new AccountRepository();
return _accountRepository.GetEntityFromDatabaseBy(id);
}
}
When you try to test this method you will find that there are a lot of complications:
1. There must be a database already set up.
2. Your database needs to have the table that has the entity you're looking for.
3. The id that you are using for your test must exist, if you delete it for whatever reason then your automated test is now broken.
If instead you have something like the following:
public interface IAccountRepository
{
AccountEntity GetAccountFromDatabase(long id);
}
public class AccountRepository : IAccountRepository
{
public AccountEntity GetAccountFromDatabase(long id)
{
//... some DB implementation here
}
}
public class MyClass
{
private readonly IAccountRepository _accountRepository;
public MyClass(IAccountRepository accountRepository)
{
_accountRepository = accountRepository;
}
public AccountEntity GetAccountEntityBy(long id)
{
return _accountRepository.GetAccountFromDatabase(id)
}
}
Now that you have that you can test the MyClass class in isolation without the need for a database to be in place.
How is this beneficial? For example you could do something like this (assuming you are using Visual Studio, but the same principles apply to NUnit for example):
[TestClass]
public class MyClassTests
{
[TestMethod]
public void ShouldCallAccountRepositoryToGetAccount()
{
FakeRepository fakeRepository = new FakeRepository();
MyClass myClass = new MyClass(fakeRepository);
long anyId = 1234;
Account account = myClass.GetAccountEntityBy(anyId);
Assert.IsTrue(fakeRepository.GetAccountFromDatabaseWasCalled);
Assert.IsNotNull(account);
}
}
public class FakeRepository : IAccountRepository
{
public bool GetAccountFromDatabaseWasCalled { get; private set; }
public Account GetAccountFromDatabase(long id)
{
GetAccountFromDatabaseWasCalled = true;
return new Account();
}
}
So, as you can see you are able, very confidently, to test that the MyClass class uses an IAccountRepository instance to get an Account entity from a database without the need to have a database in place.
There are a million things you can still do here to improve the example. You could use a Mocking framework like Rhino Mocks or Moq to create your fake objects instead of coding them yourself like I did in the example.
By doing this the MyClass class is completely independent of the AccountRepository so that's when the loosley coupled concept comes into play and your application is testable and more maintainable.
With this example you can see the benefits of IoC in itself. Now if you DO NOT use an IoC container you do have to instantiate all the dependencies and inject them appropriately in a Composition Root or configure an IoC container so it can do it for you.
Regards.
Is it possible to mock the enterprise library 5 version of 'Database'? If so... how?
There is no IDatabase interface (which is a mystery as I though Microsoft P&P would be more on the ball about testability benefits of exposing such an interface).
I have a Repository class which used EntLib 5 Data Access Application Block.
I am retro fitting unit tests into this class and need to mock out the dependency on the Database object. This class is now passed the Database via its constructor and uses a Database object to perform operations on the Db.
I use the following to resolve an instance of the Database to be passed to my Repository:
Container.RegisterType<IFooRepository, FooRepository>(
new InjectionConstructor(
EnterpriseLibraryContainer.Current.GetInstance<Database>("FooDbConnStr")
)
);
I don't wish these unit tests to become integration tests.
I have tried using Moq to create a dynamic mock of the Database type, but this has proved tricky as Database requires a connection string and a DbProviderFactory in its constructor. Maybe if there was such a thing as a MockDbProviderFactory.
This is the form that the unit test is taking:
Aside: I also find the use of a static logger class very difficult to test. Hopefully I am missing some trick here, but I must say I am disappointed with testability thus far.
FWIW, I was able to mock a SqlDatabase using Moq. SqlDatabase has a SqlClientPermission attribute which does not play well with Castle Windsor (used by Moq). I had to explicitly instruct Castle to ignore the SqlClientPermission attribute to get the test to work (see line 1 in the example below). Below is a sample unit test (borrowing Steven H's example).
[TestMethod]
public void FooRepo_CallsCorrectSPOnDatabase()
{
Castle.DynamicProxy.Generators.AttributesToAvoidReplicating.Add(typeof(System.Data.SqlClient.SqlClientPermissionAttribute));
var mockSqlDb = new Mock<SqlDatabase>("fake connection string");
mockSqlDb.Setup(s => s.GetStoredProcCommand("sp_GetFoosById"));
var sut = new FooRepository(mockSqlDb);
sut.LoadFoosById(1);
mockSqlDb.Verify(s => s.GetStoredProcCommand("sp_GetFoosById"), Times.Once(), "Stored Procedure sp_GetFoosById was not invoked.");
}
I used FakeItEasy http://code.google.com/p/fakeiteasy/.
I created a mock of SqlDatabase (inherits from Database with a friendlier constructor) passed it to the FooRepostory, called the function under test and asserted expected calls that were made to the Database.
[Test]
public void FooRepo_CallsCorrectSPOnDatabase()
{
var mockDb = A.Fake<SqlDatabase>(x => x.WithArgumentsForConstructor(new object[] { "fakeconnStr" }));
var sut = new FooRepository(mockDb);
sut.LoadFoosById(1);
A.CallTo(() => mockDb.GetStoredProcCommand(Db.SProcs.GetFoosById)).MustHaveHappened(Repeated.Once);
}
Database is an abstract base class, and DbProviderFactory is also abstract, so you can mock them both out. As long as you mock out the operations that you're calling on the Database type (just about everything there is virtual so you should be ok there) you don't actually need to do anything in the provider factory. And the connection string can just be empty or null or whatever.
I personally loaded up the source code and used ReSharper to Extract Interface for the Database object. It rebuilt and I used my custom binaries. Wala - An interface! Hint: Interfaces are simple to mock. Why Microsoft P&P group didn't do this, I do not know.