Unit testing class that does not have an output - c#

Often times, a class would not have a direct output; it manipulates its dependencies, making them do things.
For example:
internal interface IEmailer
{
void SendEmail();
}
class ReportSender
{
public IEmailer Emailer { get; set; }
public ReportSender(IEmailer emailerToUse)
{
Emailer = emailerToUse;
}
public void SendReport()
{
// Do whatever is needed to create the report
Emailer.SendEmail();
}
}
Creating a mock of IEmailer and make it expect IEmailer.SendEmail() seem to be exposing too much of the innards of the class and making the test fragile.
But I can't think of any other way to test this class.
How should we write unit tests for such a class?

Making a mock of IEmailer doesn't by itself expose too much of the class. Rather, it makes it open for extensibilty.
There's a certain tendendency that heavily relying on interaction-based testing (i.e. mocks) makes tests more fragile, but this is more of a design issue than an issue with mocks.
The Hollywood Principle can be really helpful here, because if your dependencies are mostly designed around void methods, dynamic mocks like Moq or Rhino Mocks will generally just ignore the method calls unless you specifically tell them to care about a particular one.

Using Mock objects is the correct way to write the unit test for this method. You don't want your test to actually send an email. Mock objects let you break dependencies between different classes for the purposes of unit testing.
Here's an example using Rhino Mocks.
http://www.ayende.com/projects/rhino-mocks.aspx
IEmailer emailer = MockRepository.GenerateMock<IEmailer>();
emailer.Expect(x => x.SendEmail());
ReportSender reportSender = new ReportSender();
reportSender.Emailer = emailer;
reportSender.SendReport();
emailer.VerifyAllExpectations();

Creating a mock of IEmailer and make it expect IEmailer.SendEmail()
is exactly the way you would test that.
since these are UNIT tests, you are not exposing too much. you are supposed to be exercising all the functions of the unit to be tested, and it's alright if you have internal knowledge of the unit.

I'm not very experienced with unit testing yet, so this might not be too helpful... but it seems to me your suggestion of mocking out the dependency is on the right track. You can then probe the state of the mocked dependencies after the operation completes, to determine whether or not the IEmailer performed the expected manipulations on them?

Creating a mock IEmailer and expecting a call to SendEmail is the proper way to test this scenario.

Creating a mock of IEmailer and make it expect IEmailer.SendEmail() seem to be exposing too much of the innards of the class and making the test fragile.
Then why are you exposing a public property requiring an internal interface?
Make the interface public and your implementations of them internal.

Related

Are interfaces necessary for mocks in unit test?

I have read that you need to define interfaces in order to mock types but I am not sure how to interpret that.
For example, to mock FileSystem, instead of directly calling some I/O method, I can pass the object to the method and then mock it when calling from my test.
Why are unit test examples (like the one from SO question below), use interfaces?
void DoIt(IZipper zipper, IFileSystem fileSystem, IDllRunner runner)
{
string path = zipper.Unzip(theZipFile);
IFakeFile file = fileSystem.Open(path);
runner.Run(file);
}
Could I not simply use arguments of respective types, and inject the object then?
E.g. in the GUICE guide, they advise to remove constructor work (e.g. no field inicialization with "new" keyword), but use parameters istead.
It depends on your mocking framework. Using Moq, you can mock concrete types as long as they aren't sealed and the members you want to mock are virtual. Interfaces are generally preferred because their members don't need to (and can't) be marked as virtual. (There are other reasons to prefer interfaces such as to keep the coupling between your classes loose)
https://github.com/Moq/moq4/wiki/Quickstart
Update
Generally you will mock an instance of a type. Therefore you can't test static method calls like FileStream.Open because there is no instance to mock.
Update
Frameworks like Moq rely on inheritance to generate the mocks. That's why methods need to be virtual. If you want to mock static or private methods, try Microsoft Fakes.
https://msdn.microsoft.com/en-us/library/hh549175.aspx
It is not must to have interface as dependency but that's recommended and widely followed practice.
Using interface and base classes as dependency helps you creating lossely couple design.
Loosely coupled design makes it possible to create modules/layers of application without depending on the implementation details about other layer.
This also makes it super easy to test the piece of code in isolation without worrying about how other layer would work or react.
This type of testing is called unit testing.
If you have dependency on concrete class then you can't unit test code in isolation. Such tests are prone to fail whenever implementation of dependency changes. If your code is dependent on actual file system class or data access class which connects to actual db then there are chances that the unit tests will fail when file is not accessible or db server is down or data is currupted.
This even won't be called unit testing. It is called integration testing.
As I mentioned, while testing code in isolation you don't need to worry about how the dependency works. That's why, while unit testing the dependencies are mocked. Also dependencies must not be an interface. It can be a base class too. When you mock dependency, mocks do not have actual implementation of any of the functionality. How many ways you can create mocks, is a different topics altogether.
Using mocks, in unit testing, you just need to make sure that they behave per your expectations while you test the code your current class. So you ask the mock to behave the way you want, make sure that certain methods or properties of mock called, so that you can cover all the paths of the piece of code which you are testing.
Following is a simple example of Unit Testing with dependency.
public class ProductService
{
private IProductRepository repository;
public ProductService (IProductRepository repository)
{
this.repository = repository;
}
public Product GetProductById(int productId)
{
if(productId <= 0)
return null;
var product = this.repository.GetProductById(productId);
return product;
}
}
While Creating ProductService class, even if I don't have actual implementation of IProductRepository interface, I can still unit test ProductService class as following.
public class ProductServiceTests
{
ProductService serviceToTest;
IProductRepository productRepository;
public ProductServiceTests()
{
this.productRepository = Mock<IProductRepository>();
this.serviceToTest = new ProductService(productRepository);
}
public void GetProductByIdReturnsNullIfProductIdIsZero()
{
int productid = 0;
var product = serviceToTest.GetProductById(productid);
Assert.That(product, Is.Null);
}
public void GetProductByIdReturnsNullIfProductIdIsNegative()
{
int productid = -1;
var product = serviceToTest.GetProductById(productid);
Assert.That(product, Is.Null);
}
public void GetProductByIdReturnsProductIfProductIdIsPositive()
{
var productid = 1;
var product = new Product { Id = productId };
productRepository.Setup(repo => repo.GetProductById(productid)).Returns(product); //Making sure that GetProductById method of repository is called and return an object of product as this call is part of the code which I am testing right now.
var product = serviceToTest.GetProductById(productid);
Assert.That(product, Is.Not.Null);
Assert.That(product.Id, Is.EqualTo<int>(productid));
}
}
This is an example code to illustrate the unit testing. It might not build or run as expected and I apologies for that.
edit
Found an excellent article on mocking classes https://www.wrightfully.com/how-net-mocking-frameworks-work
This should clear doubts of how class mocking is different than the interface mocking.

Unit testing object whose lifetime scope is handled by IoC container

I am using Microsoft Unit Test and have the following:
public class AccountCommandHandlers :
Handler<CreateAccountCommand>,
Handler<CloseAccountCommand>
{
public bool CreateAccountCommandWasCalled = false;
public bool CloseAccountCommandWasCalled = false;
public void Handle(CreateAccountCommand command)
{
CreateAccountCommandWasCalled = true;
}
public void Handle(CloseAccountCommand command)
{
CloseAccountCommandWasCalled = true;
}
}
[TestMethod]
public void CanRaiseInternalHandlers()
{
var iocContainer = SimpleInjectorWiringForMembus.Instance;
iocContainer.Bootstrap(
AppDomain.CurrentDomain.GetAssemblies());
var membus = MembusWiring.Instance;
membus.Bootstrap();
membus.Bus.Publish(new CreateAccountCommand() { Id = 100 });
membus.Bus.Publish(new CloseAccountCommand() { Id = 100 });
}
I am using an IoC container (Simple Injector) which handles the lifetime scope of objects. Membus wires up commands to command handlers, and resolves via the IoC container.
The above code runs and works and the command handlers set their local variables to true.
However, since Simple Injector handles the lifetime scope, I cant ask Simple Injector for an AccountCommandHandler object as it would return a new object with CreateAccountCommandWasCalled set to false.
Being new to Unit Testing what would be a more robust way to test other than setting CreateAccountCommandWasCalled as a static variable?
As the others have already mentioned, you are actually running integration tests. This isn't a problem however. Integration tests are suited for testing your IoC settings and for making sure that the different parts of your application work together.
With an integration tests however, you shouldn't be using mock or stub objects. Mocks and stubs have their uses in unit testing. A unit test is all about testing the smallest possible part of your code. Within a unit test, you use mocks to control the behavior of all dependencies that your class has. I wrote a blog a year ago that gives an introduction to the differences between integration and unit tests and how to use mocking in your tests.
In your situation, I wouldn't use the IoC container with production configuration for setting up your unit tests. Instead, I would switch to manually creating your objects in your tests and using a mocking tool like Moq to control the dependencies.
But this is also something that can be automated. A great tool is AutoFixture. 'Fixture' refers to the baseline you need to run your tests. This could be some sample data, the mocks and stubs you need and other setup code.
Mark Seemann (the developer behind AutoFixture) wrote a nice blog a couple of weeks ago about using AutoFixture together with an IoC as an Auto-mocking Container. I would advice to use something like this to structure your unit tests.
As Steven said in his comments, it sounds like you are writing an integration test, in which case it does make sense to use the IoC container.
Your test project should have its own Composition Root for the IoC configuration. You can configure your IoC container to return a mock object for AccountCommandHandlers. Your test, rather than check the boolean members, can instead check that the Handle(CreateCommand) was called at least one time. With Moq, it would look something like this:
mock.Verify(foo => foo.Handle(createAccountCommand), Times.AtLeastOnce());
If for whatever reason you can't use a mock framework with the IoC config, it would be easy to create your own mock class for this one test case.
Here's a more "philosophical" answer to your question :-)
My recommendation would be to not use the IOC container in your testing at all, if possible!
My rationale is that you need your test to have full control over the context of the test, and an IOC can take away some of this control. IMO, unit tests should be as focussed, small and predictable as possible!
Consider sending mock objects into your class under test, instead of actual classes.
If your class needs to have an internal instance of an IOC container, factor this out of the class into a "controller" of some sorts.
You could accomplish this in several ways, my favourite being using a framework like Rhino Mocks.
This way, you would actually stub out the "lifecycle" provided by the IOC at run time, in your test "setup".
So the test should have full control (through mocking and stubbing) over when objects are created or destroyed, using a framework like Rhino.
You could mock out the IOC, if this is even needed.
As a side note, one of the benefits of a well designed IOC container is that it should make unit testing easier - because it should discourage classes from relying on actual "concrete instances" of classes, and encourages the use of interchangeable interfaces instead.
You should try rely at run time on the IOC container providing the concrete implementations of the interfaces you've designed against.
Note that it's also normally important to get clarity about what you are actually testing. Unit tests should typically focus on testing the behavior of a single method on a single class.
If you're actually testing "more" than just one method on one class, for e.g. how a class interacts with other classes, it means you're most likely writing an "integration" test, not a true "unit" test.
Another note: I don't claim to be an expert at unit testing! They are incredibly useful, but I still struggle with testing more than almost any other aspect of coding.
For further reading, I highly recommend "The Art of Unit Testing" by Roy Osherove. There are others too.
The Art of Unit Testing
One question you should also ask yourself is: What do I actually want to test?
Your test suite shouldn't necessarily need to test 3rd party libs. In the above, membus was designed to deliver the messages to the handlers, tests in that library ensure that this is the case.
If you really want to test the message -> IOC handler delegation, in the case of Membus you could write a bus -> IOC adapter for testing:
public class TestAdapter : IocAdapter
{
private readonly object[] _handlers;
public TestAdapter(params object[] handlers)
{
_handlers = handlers;
}
public IEnumerable<object> GetAllInstances(Type desiredType)
{
return _handlers;
}
}
And then use it with the instances under test.
var bus =
BusSetup.StartWith<Conservative>()
.Apply<IoCSupport>(
ioc => ioc.SetAdapter(new TestAdapter(new Handler<XYZ>()))
.SetHandlerInterface(typeof (IHandler<>)))
.Construct();
where you would keep the Handler instance around to do assertions against it. OTOH if you trust the library to do its work you would simply new up the handler and test its internal logic.

Unit test a method which is on high abstraction level

A similar topic has been discussed in The value of high level unit tests and mock objects
However, I'd like to describe a specific situation and ask your opinion about how I should write a unit test.
I am developing an ordinary 3-tier application, which uses Entity Framework. Above EF, I have two layers:
Repositories: They directly access the EF ObjectContext and do all the CRUD work (actually, these classes are generated with a T4 template). All Repository class has an appropriate interface.
Managers: They implement the higher level business logic, they do not access directly the ObjectContext, rather use an appropriate Repository. Managers do not know the concrete Repository-implementation, only the interface (I use dependency injection, and mocks in the unit test).
Without further description, here is the class I'd like to write unit tests for:
public class PersonManager
{
private IPersonRepository personRepository; // This is injected.
// Constructor for injection is here.
public void ComplexMethod()
{
// High level business logic
bool result = this.SimpleMethod1();
if(result)
this.SimpleMethod2(1);
else
this.SimpleMethod2(2);
}
public bool SimpleMethod1()
{
// Doing some low-level work with the repository.
}
public void SimpleMethod2(int param)
{
// Doing some low-level work with the repository.
}
}
It is really easy to unit test SimpleMethod1 and SimpleMethod2 by instantiating the PersonManager with a mock of the PersonRepository.
But I can not find any convenient way to unit test ComplexMethod.
Do you have any recommendation about how should I do that? Or that should not be unit tested at all? Maybe I should not use the this reference for the method calls in ComplexMethod, rather access the PersonManager itself via an interface, and replace that with a mock too?
Thanks in advance for any advice.
Guillaume's answer is good (+1), but I wanted to give an additional observation. What I see in the code you've posted is the basis for a very common question from people trying to figure out (or argue against) TDD, which is:
"How/why should I test ComplexMethod() since it depends on SimpleMethod1() and SimpleMethod2(), which are already tested and have their own behavior that I'd have to account for in tests of ComplexMethod()? I'd have to basically duplicate all the tests of SimpleMethod1() and SimpleMethod2() in order to fully test ComplexMethod(), and that's just stupid."
Shortly after, they usually find out about partial mocks. Using partial mocks, you could mock SimpleMethod1() and SimpleMethod2() and then test ComplexMethod() using normal mock mechanisms. "Sounds great," they think, "This will solve my problem perfectly!". A good mock framework should strongly discourage using partial mocks in this way, though, because the reality is:
Your tests are telling you about a design problem.
Specifically, they're telling you that you've mixed concerns and/or abstraction levels in one class. They're telling you that SimpleMethod1() and SimpleMethod2() should be extracted to another class which this class depends on. No matter how many times I see this scenario, and no matter how vehemently the developer argues, the tests are proven right in the end 100% of the time.
I don't see what the problem is. You can test your complex method while mocking the repository, there is no problem.
Your would need two unit-tests, each one would use the same sequence of expectations and executions that you have in your tests of the SimpleMethod1 (I assume you already have two unit-tests for SimpleMethod1, one for a return of "true", one for "false") and also the same expectations that you have for your test SimpleMethod2 with a fixed parameter 1, or 2 respectively.
Granted, there would be some "duplication" in your testing class, but that's not a problem.
Also note your tests for SimpleMethod2 should not make any assumption for the parameter passed: in "real-life" you can have only 1 or 2 as a parameter (and that's what your unit-test for ComplexMethod would have), but your unit-tests for SImpleMethod2 should test it whatever the parameter is: any int.
And finally, if ComplexMethod is the ONLY way to call SimpleMethod1 and/or SimpleMethod2, you should consider making these private, and have only unit-tests for ComplexMethod.
Does that make sense?

Testing if another method on same object was called with testing the targetObject

public Class Test{
GetDataset(RandomBoolean uncertain);
GetDataset2();
GetDataset3();
}
where method definitions are
public virtual void GetDataset2(){}
public virtual void GetDataset3(){}
public virtual void GetDataset(RandomBoolean uncertain)
{
if (uncertain.State){
GetDataset2();
}
else{
GetDataset3();
}
}
//mocking uncertain.State to return true
//ACT
testObject.GetDataset(uncertainMock);
I want to test if GetDataset2() was called internally when I act on testObject.GetDataset();
I am not mocking the testObject because it's the test object so if I try to do
testObject.AssertWasCalled(x => x.GetDataset2());
It won't let me do this because testObject is not a mocked object.
I am using Rhino Mocks 3.5, I am definitely missing something here.
What is the best way to achieve this.
The short answer is: you can't. On the other thing usually you don't want to. When you are unit testing the class, you want to make sure that the class does its computation correctly and that it has correct side effects. You shouldn't test the internals of the class, because this causes the coupling of the real code and the tests to be too strong. The idea is that you can freely change the implementation of your class and use your tests to make sure it still works correctly. You wouldn't be able to do it if your tests inspect the internal state or flow.
You have 2 options (depending on context)
You can structure your tests in a way that they only look at externally visible behaviour
If (1) is too hard, consider refactoring GetDataset2 into a separate class. Then you would be able to mock it while testing GetDataset method.
That's generally not how unit testing with mocks works.
You should be concerned with collaborators (which you stub/mock) and with results (state changes in the case of void methods), not with the internal workings of the system under test (calls to collaborators notwithstanding).
That is both because and why you can't make those types of behavioural observations (at least not without changing your classes to accommodate testing, by exposing private members or adding state-revealing members -- not good ideas).
Besides using a partial mock via Rhino Mocks, you could also create class derived from Test that replaces the implementation of GetDataSet2() with a function that records it was called. Then check that in your test.
It is a code smell that you're doing too much in one class though.
There is some info about partial mocks here. Here are some code snippets on how to do that with RhinoMocks and Moq.
Try this:
using Rhino.Mocks;
public class TestTest {
[Test]
public void FooTest()
{
var mock = new MockRepository().PartialMock<Test>();
mock.Expect(t => t.GetDataset2());
mock.GetDataset((RandomBoolean)null);
}
}

Unit test using Moq doesn't pass, object is null, did I miss something?

The class I want to test is my ArticleManager class, specifically the LoadArticle method:
public class ArticleManager : IArticleManager
{
private IArticle _article;
public ArticleManger(IDBFactory dbFactory)
{
_dbFactory = dbFactory;
}
public void LoadArticle(string title)
{
_article = _dbFactory.GetArticleDAO().GetByTitle(title);
}
}
My ArticleDAO looks like:
public class ArticleDAO : GenericNHibernateDAO<IArticle, int>, IArticleDAO
{
public virtual Article GetByTitle(string title)
{
return Session.CreateCriteria(typeof(Article))
.Add(Expression.Eq("Title", title))
.UniqueResult<Article>();
}
}
My test code using NUnit and Moq:
[SetUp]
public void SetUp()
{
_mockDbFactory = new Mock<IDBFactory>();
_mockArticleDao = new Mock<ArticleDAO>();
_mockDbFactory.Setup(x => x.GetArticleDAO()).Returns(_mockArticleDao.Object);
_articleManager = new ArticleManager(_mockDbFactory.Object);
}
[Test]
public void load_article_by_title()
{
var article1 = new Mock<IArticle>();
_mockArticleDao.Setup(x => x.GetByTitle(It.IsAny<string>())).Returns(article1.Object);
_articleManager.LoadArticle("some title");
Assert.IsNotNull(_articleManager.Article);
}
The unit test is failing, the object _articleManager.Article is returning NULL.
Have I done everything correctly?
This is one of my first unit tests so I am probably missing something obvious?
One issue I had, was that I wanted to mock IArticleDao but since the class ArticleDao also inherits from the abstract class, if I just mocked IArticleDao then the methods in GenericNHibernateDao are not available?
Preface: I'm not familiar with using Moq (Rhino Mocks user here) so I may miss a few tricks.
I'm struggling to follow some of the code here; as Mark Seemann pointed out I don't see why this would even compile in its current state. Can you double check the code, please?
One thing that sticks out is that you're injecting a mock of IDBFactory into Article manager. You then make a chained call of:
_article = _dbFactory.GetArticleDAO().GetByTitle(title)
You've not provided an implementation of GetArticleDAO. You've only mocked the LoadByTitle bit that happens after the GetARticleDAO call. The combination of mocks and chained calls in a test are usually a sign that the test is about to get painful.
Law of Demeter
Salient point here: Respect the Law of Demeter. ArticleManager uses the IArticleDAO returned by IDBFactory. Unless IDBFactory does something really important, you should inject IArticleDAO into ArticleManager.
Misko eloquently explains why Digging Into Collaborators is a bad idea. It means you have an extra finicky step to set up and also makes the API more confusing.
Furthermore, why do you store the returned article in the ArticleManager as a field? Could you just return it instead?
If it's possible to make these changes, it will simplify the code and make testing 10x easier.
Your code would become:
public class ArticleManager : IArticleManager
{
private IArticleDAO _articleDAO
public ArticleManger(IArticleDAO articleDAO)
{
_articleDAO = articleDAO;
}
public IArticle LoadArticle(string title)
{
return _articleDAO.GetByTitle(title);
}
}
You would then have a simpler API and it'd be much easier to test, as the nesting has gone.
Making testing easier when relying on persistence
In situations where I'm unit testing code that interacts with persistence mechanisms, I usually use the repository pattern and create hand-rolled, fake, in-memory repositories to help with testing. They're usually simple to write too -- it's just a wrapper around a dictionary that implements the IArticleRepository interface.
Using this kind of technique allows your ArticleManager to use a fake persistence mechanism that behaves very similarly to a db for the purpose of testing. You can then easily fill the repository with data that helps you test the ArticleManager in a painless fashion.
Mocking frameworks are really good tools, but they're not always a good fit for setting up and verifying complicated or coherent interactions; if you need to mock/stub multiple things (particularly nested things!) in one test, it's often a sign that the test is over-specified or that a hand-rolled test double would be a better bet.
Testing is hard
... and in my opinion, doubly hard if you start with mocking frameworks. I've seen a lot of people tie themselves in knots with mocking frameworks due to the 'magic' that happens under the hood. As a result, I generally advocate staying away from them until you're comfortable with hand-rolled stubs/mocks/fakes/spies etc.
As you have currently presented the code, I can't see that it compiles - for two reasons.
The first one is probably just an oversight, but the ArticleManager class doesn't have an Article property, but I assume that it simply returns the _article field.
The other problem is this line of code:
_mockArticleDao.Setup(x => x.GetByTitle(It.IsAny<string>())).Returns(article1.Object);
As far as I can see, this shouldn't compile at all, since ArticleDAO.GetByTitle returns Article, but you are telling it to return an instance of IArticle (the interface, not the concrete class).
Did you miss something in your description of the code?
In any case, I suspect that the problem lies in this Setup call. If you incorrectly specify the setup, it never gets called, and Moq defaults to its default behavior which is to return the default for the type (that is, null for reference types).
That behavior, BTW, can be changed by setting the DefaultValue property like this:
myMock.DefaultValue = DefaultValue.Mock;
However, that's not likely to solve this problem of yours, so can you address the issues I've pointed out above, and I'm sure we can figure out what's wrong.
I am not a Moq expert but it seems to me that the problem is in you mocking ArticleDAO where you should be mocking IArticleDAO.
this is related to your question:
One issue I had, was that I wanted to mock IArticleDao but since the class ArticleDao also inherits from the abstract class, if I just mocked IArticleDao then the methods in GenericNHibernateDao are not available?
In the mock object you don't need the methods inherited from the GenericNHibernateDao class. You just need the mock object to supply the methods that take part in your test, namely: GetByTitle. You provide the behavior of this method via mocking.
Moq will not mock methods if they already exist in the type that you're trying to mock. As specified in the API docs:
Any interface type can be used for mocking, but for classes, only abstract and virtual members can be mocked.
Specifically, your mocking of GetByTitle will be ignored as the mocked type, ArticleDao, offers a (non-abstract) implementation of this method.
Thus, my advise to you is to mock the interface IArticleDao and not the class.
As mentioned by Mark Seeman, I couldn't get this to compile "as-is" as the .GetByTitle expectation returns the wrong type, resulting in a compile-time error.
After correcting this, and adding the missing Article property, the test passed - leading me to think that the core of your problem has somehow become lost in translation as you wrote it up on SO.
However, given you are reporting a problem, I thought I'd mention an approach that will get Moq itself to help you identify your issue.
The fact you are getting a null _articleManager.Article is almost certainly because there is no matching expectation .GetByTitle. In other words, the one that you do specify is not matching.
By switching your mock to strict mode, Moq will raise an error the moment a call is made that has no matching expectation. More importantly, it will give you full information on what the unmatched call was, including the value of any arguments. With this information you should be able to immediately identify why your expectation is not matching.
Try running the test with the "failing" mock set as strict and see if it gives you the information you need to solve the problem.
Here is a rewrite of your test, with the mock as strict (collapsed into a single method to save space):
[Test]
public void load_article_by_title()
{
var article1 = new Mock<Article>();
var mockArticleDao = new Mock<ArticleDAO>(MockBehavior.Strict); //mock set up as strict
var mockDbFactory = new Mock<IDBFactory>(MockBehavior.Strict); //mock set up as strict
mockDbFactory.Setup(x => x.GetArticleDAO()).Returns(mockArticleDao.Object);
mockArticleDao.Setup(x => x.GetByTitle(It.IsAny<string>())).Returns(article1.Object);
var articleManager = new ArticleManager(mockDbFactory.Object);
articleManager.LoadArticle("some title");
Assert.IsNotNull(articleManager.Article);
}

Categories