This question already has answers here:
What are the differences between mocks and stubs on Rhino Mocks?
(5 answers)
Closed 9 years ago.
I have lately become very interested in testing and Im now trying to learn to do unit testing in the best way possible. I use NUnit together with Rhino Mocks. I have also been reading a lot over here at Stackoverflow but havent been able to find a clear answer to my question.
What I wonder is if I have a method like the below, should I mock the OfficeClass dependency and also test GetAllOffices or only use a stub for the dependency and verify that the method GetAllOffices has been called and that I indeed get the offices back that I expected from my setup for the stub?
public Offices GetAllOffices()
{
try
{
var offices = officeClass.GetAllOffices();
return offices;
}
}
Will it make any difference if the OfficeClass is just another POCO or if it is let say a web service in sence of mocking vs stubbing?
Long question short: When to Mock and when to Stub in unit testing?
Mocks use a framework to generate a "mock" of your dependency. For example if officeClass is a repository for your data then you can use a mock framework (I use MOQ) to generate a mock of your repository. That's why using interfaces for your dependency make it ideal for testing, the mocking framework can easily make a mock of an interface for testing.
With stubs as I understand it, you manually stub out your dependency and create canned responses. For example if you have an interface IOfficeClass and you create a new class that inherits from it, you can inject that class into your service to allow you to use it.
Again things like web services should be wrapped in some interface (like the IRepository pattern), that will allow you to easily test your logic without needing to hit the web service. The same with POCO classes.
So for example in your case you would have:
public interface IOfficeRepository
{
IQueryable<Office> GetAll();
}
And for your service
public class MyOfficeService
{
private readonly IOfficeRepository officeRepostiory;
public MyOfficeService(IOfficeRepository repository)
{
this.officeRepostiory = repository;
}
public Office GetOffice(int id)
{
return this.officeRepostiory.GetAll().SingleOrDefault(o => o.Id == id);
}
}
This way you can also change your underlying datasource without having to modify your main application or business logic code.
Your unit test would look something like this using moq:
[TestClass]
public class OfficeUnitTest
{
private MyOfficeService service;
[TestInitialize]
public void Setup()
{
var officeRepository = new Mock<IOfficeRepository>();
var office = new List<Office>();
office.Add(new Office{ Id = 1 });
officeRepository.Setup(m => m.GetAll()).Returns(office.AsQueryable());
this.service = new MyOfficeService(officeRepository.Object);
}
[TestMethod]
public void TestGetById()
{
Assert.IsNotNull(service.GetOffice(1));
// my mock will never return a value for 2
Assert.IsNull(service.GetOffice(2));
}
}
You can read more about mocks and stubs below:
http://martinfowler.com/articles/mocksArentStubs.html
http://msdn.microsoft.com/en-us/library/ff649690.aspx
Related
I'm working with big legacy projects.
I've started writing unit tests with xUnit.
Also, I'm using the Moq framework.
I've read a lot of articles here, but have not found a clear answer. I stuck with understanding how can I do mocks for two IDisposable objects inside a tested method? The method I would like to test:
public class SomeService: ISomeService
{
...
public async Task<Settings> GetSettings(UserIdentity user)
{
SettingsDBModel dbModel;
using (DBHelperAsync dbHelper = new DBHelperAsync(user))
{
using (DBHelperReaderAsync reader = await dbHelper.ExecuteReader("Stored procedure Name", new { UserID = user.UserID }))
{
dbModel = await reader.GetResult<SettingsDBModel>();
}
}
var settings = new Settings(dbModel);
return settings;
}
...
}
I want to reader.GetResult() method returns some fake data. Any thought how should be implemented of mocks for DBHelperAsync and DBHelperReaderAsync objects?
The class under test should be refactored to decouple it from the DBHelperAsync implementation concern. Classes should depend on abstractions and not concretions.
An abstract explicit dependency should be injected and configured accordingly for run time code. The would now allow the class under test to be flexible enough to be easily tested in isolation. (Explicit Dependency Principle).
If the legacy classes are unable to be modified then they should be wrapped in abstraction that can be modified and then injected into the classes under test.
The provided code above needs a IDBHelperAsyncFactory abstraction that would be injected into the class and used to create the disposable DBHelperAsync which should have also been derived from a disposable abstraction interface IDBHelperAsync : IDisposable.
That would allow those abstractions to be easily mocked/stubbed while testing.
This question follows on from my previous question here: How to use OneTimeSetup? and specifically one of the answerers answer. Please see the code below:
[TestFixture]
public class MyFixture
{
IProduct Product;
[OneTimeSetUp]
public void OneTimeSetUp()
{
IFixture fixture = new Fixture().Customize(new AutoMoqCustomization());
Product = fixture.Create<Product>();
}
//tests to follow
}
Is AutoMoq used to create mocks only? The reason I ask is because I was reading a question on here earlier where the answerer implied that it is also used to create normal types i.e. not Mocks.
I want to test the Core element of my Onion, which has no dependencies. Therefore should I be using AutoFixture?
The AutoMoq Glue Library gives AutoFixture the additional capabilities of an Auto-Mocking Container; that is, not only can it compose normal objects for you - it can also supply mock objects to your objects, should they be so required.
AutoFixture itself is not an Auto-Mocking Container, but rather a library that automates the Fixture Setup phase of the Four Phase Test pattern, as described in xUnit Test Patterns. It also enables you to automate code associated with the Test Data Builder pattern.
It was explicitly designed as an alternative to Implicit Setup, so I think it makes little sense to use it together with a setup method and mutable class field as this question suggests. In other words, the whole point of AutoFixture is that it enables you to write independent unit tests like this:
[TestFixture]
public class MyFixture
{
[Test]
public void MyTest()
{
var fixture = new Fixture().Customize(new AutoMoqCustomization());
var product = fixture.Create<Product>();
// Use product, and whatever else fixture creates, in the test
}
}
You definitely can use it to test your units even when they have no dependencies, but in that case, you probably don't need the AutoMoq Customization.
I have a Lin2Sql DataContext that I am using to get all my data from a sql database however I am struggling to find a way to successfully Mock this so that I can create relevant Unit Tests.
In my data access objects that I am wanting to test I am refreshing the context each time and I am finding it difficult to find a simple suitable way to mock this.
Any help with this matter will be greatly appreciated.
Mocking the linq-to-sql context is indeed a huge task. I usually work around it by letting my unit tests run against a separate database copy, with data specially crafted to fit the unit tests. (I know it can be argued that it's no longer unit tests, but rather integration tests, but I don't care as long as I get the code tested).
To keep the database in a known state I wrap each test in a TransactionScope which is rolled back at the end of the test. That way the state of the database is never changed.
A sample test method looks like this:
[TestMethod]
public void TestRetire()
{
using (TransactionScope transaction = new TransactionScope())
{
Assert.IsTrue(Car.Retire("VLV100"));
Assert.IsFalse(Car.Retire("VLV100"));
// Deliberately not commiting transaction.
}
}
The code is from a blog post about the method I wrote some time ago: http://coding.abel.nu/2011/12/using-transactions-for-unit-tests/
Since you request a way to mock a DataContext I assume that you really want to do some unit tests and not integration tests.
Well, I will tell you how to accomplish this, but first I would like to encourage you to read the following links, they are all about writing clean testable code.
http://misko.hevery.com/code-reviewers-guide/
http://misko.hevery.com/attachments/Guide-Writing%20Testable%20Code.pdf
And check the links from this response:
https://stackoverflow.com/a/10359288/1268570
Watch the clean code talks from Misko Hevery (given to the Google people)
http://www.youtube.com/watch?v=wEhu57pih5w&feature=player_embedded
http://www.youtube.com/watch?v=RlfLCWKxHJ0&feature=player_embedded
http://www.youtube.com/watch?v=-FRm3VPhseI&feature=player_embedded
http://www.youtube.com/watch?v=4F72VULWFvc&feature=player_embedded
One thing that I used to repeat to myself and to my fellows at work, is that anyone can write a unit test, because they are silly easy to write. So a simple test is essentially all about making some comparisons and throw exceptions if the results fails, anyone can do that. Of course, there are hundreds of frameworks to help us write those tests in an elegant way. But the real deal, and the real effort shroud be put on learn how to write clean testable code
Even if you hire Misko Hevery to help you write tests, he will have a real hard time writing them if your code is not test-friendly.
Now the way to mock a DataContext objects is: do not do it
Instead wrap the calls using a custom interface instead:
public interface IMyDataContextCalls
{
void Save();
IEnumerable<Product> GetOrders();
}
// this will be your DataContext wrapper
// this wll act as your domain repository
public class MyDataContextCalls : IMyDataContextCalls
{
public MyDataContextCalls(DataClasses1DataContext context)
{
this.Context = context;
}
public void Save()
{
this.Context.SubmitChanges();
}
public IEnumerable<Product> GetOrders()
{
// place here your query logic
return this.Context.Products.AsEnumerable();
}
private DataClasses1DataContext Context { get; set; }
}
// this will be your domain object
// this object will call your repository wrapping the DataContext
public class MyCommand
{
private IMyDataContextCalls myDataContext;
public MyCommand(IMyDataContextCalls myDataContext)
{
this.myDataContext = myDataContext;
}
public bool myDomainRule = true;
// assume this will be the SUT (Subject Under Test)
public void Save()
{
// some business logic
// this logic will be tested
if (this.myDomainRule == true)
{
this.myDataContext.Save();
}
else
{
// handle your domain validation errors
throw new InvalidOperationException();
}
}
}
[TestClass]
public class MyTestClass
{
[TestMethod]
public void MyTestMethod()
{
// in this test your mission is to test the logic inside the
// MyCommand.Save method
// create the mock, you could use a framework to auto mock it
// or create one manually
// manual example:
var m = new MyCommand(new MyFakeDataContextFake());
m.Invoking(x => x.Save())
//add here more asserts, maybe asserting that the internal
// state of your domain object was changed
// your focus is to test the logic of the domain object
.ShouldNotThrow();
//auto mock example:
var fix = new Fixture().Customize(new AutoMoqCustomization());
var sut = fix.CreateAnonymous<MyCommand>();
sut.myDomainRule = false;
sut.Invoking(x => x.Save())
.ShouldThrow<InvalidOperationException>();
}
public class MyFakeDataContextFake : IMyDataContextCalls
{
public void Save()
{
// do nothing, since you do not care in the logic of this method,
// remember your goal is to test the domain object logic
}
public IEnumerable<Product> GetOrders()
{
// we do not care on this right now because we are testing only the save method
throw new NotImplementedException();
}
}
}
Notes:
When you declare your IMyDataContextCalls interface you are actually abstracting the use of a DataContext, therefore this interface should contain only POCO objects (most of the time), if you follow this approach your interfaces will be decoupled from any undesired dependency.
In the specific MyDataContextCalls implementation, you are explicitly using a DataClasses1DataContext context, but you are free to change the implementation at any time and that won't affect your external code, and that's because you are always working with the IMyDataContextCalls interface instead. So at any time you could change for example this implementation for another one using the wonderful NHibernate =) or the poor ef or a mock one
At last, but not least. please double check my code, and you will notice that there are no new operators in the domain objects. This is a rule of dumb when writing test friendly code: decouple the responsibility of creating objects outside of your domain objects
I personally use three frameworks on every project and on every test I write, I really recommend them:
AutoFixture
Moq
FluentAssertions
For example, in the code above, I showed you how to write a manual fake for your repository, but that clearly is something we do not want to do in a real project, imagine the number of objects you would have to code in order to write your tests.
Instead use the power of AutoFixture combined with Moq:
This line: var m = new MyCommand(new MyFakeDataContextFake());
Will become:
var fixture = new Fixture().Customize(new AutoMoqCustomization());
var sut = fixture.CreateAnonymous<MyCommand>();
And that's it, this code will automatically create mocks for all the objects needed in the constructor of MyCommand.
In short, you don't mock DataContext. You extract interface from it and mock that interface using some collections for entity sets, and then verify contents of those collections.
I use NUnit for my unit-testing. In my current project, I have a problem in which almost all of the functions I want to test are connected to the database. Meanwhile, the database is bounded when the application is started.
I am so confused now, I have read regarding mock unit-testing, but don't know exactly how to handle this problem. Any solution for me here?
To make things harder, this database is static, not as parameter of my method... This makes me so confused
You might want to review the architecture of your application. Make sure the database layer is loosely coupled, for example by using interfaces. This will make it possible to write stubs or mocks for your database layer.
The normal solution to this is to keep your data layer in a separate class that implements a well-known interface. For instance:
public interface IDataLayer
{
IEnumerable<Customer> GetAllCustomers();
Order GetOrderById(int id);
}
You will implement the interface as normal for your actual data access
public class SqlServerDataLayer : IDataLayer
{
// implementation
}
But in your tests, you can now use a mocking framework like Moq or RhinoMocks to set up a mock data layer that returns test data. This ensures you are only testing how your classes use the data, which is ideal.
[Test]
public void TestGettingCustomersRefreshesViewModel()
{
//arrange
var mockDb = new Mock<IDataLayer>();
mockDb.Setup(db => db.GetAllCustomers()).Returns(new List<Customer>());
underTest.DataRepository = mockDb.Object;
//act
underTest.GetCustomerCommand.Execute();
//assert
Assert.That(underTest.CustomerList != null);
}
I'm trying my hand at behavior driven development and I'm finding myself second guessing my design as I'm writing it. This is my first greenfield project and it may just be my lack of experience. Anyway, here's a simple spec for the class(s) I'm writing. It's written in NUnit in a BDD style instead of using a dedicated behavior driven framework. This is because the project targets .NET 2.0 and all of the BDD frameworks seem to have embraced .NET 3.5.
[TestFixture]
public class WhenUserAddsAccount
{
private DynamicMock _mockMainView;
private IMainView _mainView;
private DynamicMock _mockAccountService;
private IAccountService _accountService;
private DynamicMock _mockAccount;
private IAccount _account;
[SetUp]
public void Setup()
{
_mockMainView = new DynamicMock(typeof(IMainView));
_mainView = (IMainView) _mockMainView.MockInstance;
_mockAccountService = new DynamicMock(typeof(IAccountService));
_accountService = (IAccountService) _mockAccountService.MockInstance;
_mockAccount = new DynamicMock(typeof(IAccount));
_account = (IAccount)_mockAccount.MockInstance;
}
[Test]
public void ShouldCreateNewAccount()
{
_mockAccountService.ExpectAndReturn("Create", _account);
MainPresenter mainPresenter = new MainPresenter(_mainView, _accountService);
mainPresenter.AddAccount();
_mockAccountService.Verify();
}
}
None of the interfaces used by MainPresenter have any real implementations yet. AccountService will be responsible for creating new accounts. There can be multiple implementations of IAccount defined as separate plugins. At runtime, if there is more than one then the user will be prompted to choose which account type to create. Otherwise AccountService will simply create an account.
One of the things that has me uneasy is how many mocks are required just to write a single spec/test. Is this just a side effect of using BDD or am I going about this thing the wrong way?
[Update]
Here's the current implementation of MainPresenter.AddAccount
public void AddAccount()
{
IAccount account;
if (AccountService.AccountTypes.Count == 1)
{
account = AccountService.Create();
}
_view.Accounts.Add(account);
}
Any tips, suggestions or alternatives welcome.
When doing top to down development it's quite common to find yourself using a lot of mocks. The pieces you need aren't there so naturally you need to mock them. With that said this does feel like an acceptance level test. In my experience BDD or Context/Specification starts to get a bit weird at the unit test level. At the unit test level I'd probably be doing something more along the lines of...
when_adding_an_account
should_use_account_service_to_create_new_account
should_update_screen_with_new_account_details
You may want to reconsider your usage of an interface for IAccount. I personally stick
with keeping interfaces for services over domain entities. But that's more of a personal preference.
A few other small suggestions...
You may want to consider using a Mocking framework such as Rhino Mocks (or Moq) which allow you to avoid using strings for your assertions.
_mockAccountService.Expect(mock => mock.Create())
.Return(_account);
If you are doing BDD style one common pattern I've seen is using chained classes for test setup. In your example...
public class MainPresenterSpec
{
// Protected variables for Mocks
[SetUp]
public void Setup()
{
// Setup Mocks
}
}
[TestFixture]
public class WhenUserAddsAccount : MainPresenterSpec
{
[Test]
public void ShouldCreateNewAccount()
{
}
}
Also I'd recommend changing your code to use a guard clause..
public void AddAccount()
{
if (AccountService.AccountTypes.Count != 1)
{
// Do whatever you want here. throw a message?
return;
}
IAccount account = AccountService.Create();
_view.Accounts.Add(account);
}
The test life support is a lot simpler if you use an auto mocking container such as RhinoAutoMocker (part of StructureMap) . You use the auto mocking container to create the class under test and ask it for the dependencies you need for the test(s). The container might need to inject 20 things in the constructor but if you only need to test one you only have to ask for that one.
using StructureMap.AutoMocking;
namespace Foo.Business.UnitTests
{
public class MainPresenterTests
{
public class When_asked_to_add_an_account
{
private IAccountService _accountService;
private IAccount _account;
private MainPresenter _mainPresenter;
[SetUp]
public void BeforeEachTest()
{
var mocker = new RhinoAutoMocker<MainPresenter>();
_mainPresenter = mocker.ClassUnderTest;
_accountService = mocker.Get<IAccountService>();
_account = MockRepository.GenerateStub<IAccount>();
}
[TearDown]
public void AfterEachTest()
{
_accountService.VerifyAllExpectations();
}
[Test]
public void Should_use_the_AccountService_to_create_an_account()
{
_accountService.Expect(x => x.Create()).Return(_account);
_mainPresenter.AddAccount();
}
}
}
}
Structurally I prefer to use underscores between words instead of RunningThemAllTogether as I find it easier to scan. I also create an outer class named for the class under test and multiple inner classes named for the method under test. The test methods then allow you to specify the behaviors of the method under test. When run in NUnit this gives you a context like:
Foo.Business.UnitTests.MainPresenterTest
When_asked_to_add_an_account
Should_use_the_AccountService_to_create_an_account
Should_add_the_Account_to_the_View
That seems like the correct number of mocks for a presenter with a service which is supposed to hand back an account.
This seems more like an acceptance test rather than a unit test, though - perhaps if you reduced your assertion complexity you would find a smaller set of concerns being mocked.
Yes, your design is flawed. You are using mocks :)
More seriously, I agree with the previous poster who suggests your design should be layered, so that each layer can be tested separately. I think it is wrong in principle that testing code should alter the actual production code -- unless this can be done automatically and transparently the way code can be compiled for debug or release.
It's like the Heisenberg uncertainty principle - once you have the mocks in there, your code is so altered it becomes a maintenance headache and the mocks themselves have the potential to introduce or mask bugs.
If you have clean interfaces, I have no quarrel with implementing a simple interface that simulates (or mocks) an unimplemented interface to another module. This simulation could be used in the same way mocking is, for unit testing etc.
You might want to use MockContainers in order to get rid of all the mock management, while creating the presenter. It simplifies unit tests a lot.
This is okay, but I would expect an IoC automocking container in there somewhere. The code hints at the test writer manually (explicitly) switching between mocked and real objects in tests which should not be the case because if we are talking about a unit test (with unit being just one class), it's simpler to just auto-mock all other classes and use the mocks.
What I'm trying to say is that if you have a test class that uses both mainView and mockMainView, you don't have a unit test in the strict sense of the word -- more like an integration test.
It is my opinion that if you find yourself needing mocks, your design is incorrect.
Components should be layered. You build and test components A in isolation. Then you build and test B+A. Once happy, you build layer C and test C+B+A.
In your case you shouldn't need a "_mockAccountService". If your real AccountService has been tested, then just use it. That way you know any bugs are in MainPresentor and not in the mock itself.
If your real AccountService hasn't been tested, stop. Go back and do what you need to ensure it is working correctly. Get it to the point where you can really depend on it, then you won't need the mock.