Mocking an object constructed inside a method call - c#

I'm new to Rhino Mocks and mocking in C# though not in general. I'm writing unit tests for a class MyClasswhich internally creates other objects as private fields. I've unit tested those classes separately but not how MyClass interacts with them...
class MyClass
{
public void Method1()
{
var o = new OtherClass();
o.Method2();
o.Method3();
}
}
Note that I don't pass OtherClass as a ctor argument and I don't really want to... creating these objects is something the class does, I don't really want an external agent injecting them.
Does Rhino Mocks allow me to somehow mock OtherClass in this scenario from a unit test, so I can determine instances are created and interacted with correctly?

Disclaimer I work at TypeMock.
It's very simple to fake a future Instance when using Typemock Isolator, actually it can be done in one line :
var classUnderTest = new MyClass();
// Faking future OtherClass
var fakeOther = Isolate.Fake.NextInstance<OtherClass>();
And you can read more about it here.

No, Rhinomocks mocks doesn't support this capability. Rhinomocks/Moq/FakeItEasy/NSubstitute are all proxy based tools which means non of them are able to isolate your code without refactoring.
To be able to isolate without refactoring you need to use code weaving tools such as Typemock Isolator, Msfakes and etc...
Somehow it is not so popular in the community to combine 2 mocking frameworks in the same project, however when I was in the .net world I usually combine Rhinomocks and Msfakes together;
Rhinomocks as a default Mocking framework
Msfakes only where it is necessary(for regular cases Rhinomocks is better....); static/sealed and etc...

Related

Is it necessary to mock all and every dependency in Unit Tests?

I'm trying to create a unit test for an ASP.NET that has the following constructor definition (filled with Ninject when running the real application):
public OrderController(IViewModelFactory modelFactory, INewsRepository repository, ILoggedUserHelper loggedUserHelper,
IDelegateHelper delegateHelper, ICustomerContextWrapper customerContext) {
this.factory = modelFactory;
this.loggedUserHelper = loggedUserHelper;
this.delegateHelper = delegateHelper;
this.customerContext = customerContext;
}
I want to test the methods inside the OrderController class, but in order to isolate it, I have to mock all and every of those dependencies, which becomes outright ridiculous (having to also mock subdependencies probably).
In this case, which is the best practice to Unit Test this class?
Well, you have to provide test doubles for all dependencies, not necessarily mocks.
Luckily,this is the 21st century and there are tools to make the job easier for us. You can use AutoFixture to create an instance of OrderController and inject mocks as necessary.
var fixture = new Fixture().Customize(new AutoConfiguredMoqCustomization());
var orderController = fixture.Create<OrderController>();
Which, basically, is equivalent to:
var factory = new Mock<IViewModelFactory>();
var repository = new Mock<INewsRepository>();
var delegateHelper = new Mock<IDelegateHelper >();
var customerContext = new Mock<ICustomerContextWrapper >();
var orderController = new OrderController(factory.Object, repository.Object, delegateHelper.Object, customerContext.Object);
If those dependencies depend on other types, those will be setup as well. AutoFixture with the AutoConfiguredMoqCustomization customization will build an entire graph of dependencies.
If you need access to, say, the repository mock, so you can do some additional setups or assertions on it later, you can freeze it. Freezing a type will make the fixture container contain only one instance of that type, e.g.:
var fixture = new Fixture().Customize(new AutoConfiguredMoqCustomization());
var repositoryMock = fixture.Freeze<Mock<INewsRepository>>();
repositoryMock.Setup(x => x.Retrieve()).Returns(1);
//the frozen instance will be injected here
var orderController = fixture.Create<OrderController>();
repositoryMock.Verify(x => x.Retrieve(), Times.Once);
I've used Moq in these examples, but AutoFixture also integrates with NSubstitute, RhinoMock and Foq.
Disclosure: I'm one of the project's contributors
No, you don't. The different concepts of test object implementations you can use are known as Test Doubles. Mocks are just one type of Test Double as defined by Gerard Meszaros in his book:
Dummy objects are passed around but never actually used. Usually they are just used to fill parameter lists.
Fake objects actually have working implementations, but usually take some shortcut which makes them not suitable for production (an InMemoryTestDatabase is a good example).
Stubs provide canned answers to calls made during the test, usually not responding at all to anything outside what's programmed in for the test.
Spies are stubs that also record some information based on how they were called. One form of this might be an email service that records how many messages it was sent.
Mocks are pre-programmed with expectations which form a specification of the calls they are expected to receive. They can throw an exception if they receive a call they don't expect and are checked during verification to ensure they got all the calls they were expecting.
You only need to give as many stubs, fakes and dummies as required for your test to pass.
Dummies take very little work to generate and may be enough to cover your scenario. An example would be a constructor that takes an IEmailer and an ILogWriter. If you're only testing the Log method, you only need to provide enough of an implementation of IEmailer in order for the test to not throw Argument exceptions.
Also, regarding your point about sub-dependencies... Moq will take care of that for you, because Moq implementations of your interface won't take dependencies.

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.

Mocking ANY class use in Java (specifically in Android)

I am coming from the .NET world (C#) to Java (Android development).
Many mocking frameworks and tools from the .NET space allow replacing/overriding class/method usage without injecting any mock objects into tested methods (Microsoft Fakes is one).
For example, in the following method:
public void SomeMethod()
{
new SomeOtherClass().Do("This is a test!");
}
Calling the SomeOtherClass().Do method can be made to return a specific value or to behave in a certain manner, even though i have not injected a mock object for this class into this method.
Using Microsoft Fakes for example, this can be done by code simliar to this:
using (ShimsContext.Create())
{
// decide what to do when Do() gets called
System.Fakes.ShimSomeOtherClass.Do = str => ....
new SomeOtherClass().Do("blabla");
}
As far as i've seen in the Java/Android mocking world, doing something like that is impossible. I would have to refactor all my code to inject its dependencies for every method.
While this may be a good practice indeed in some places, it would be impossible to do in all code locations.
Is there any way to achieve this with Java?
Frameworks i'm working with: Mockito, PowerMock, Robolectric
You can mock the instantiation of a new object with PowerMock using expectNew()
http://code.google.com/p/powermock/wiki/MockConstructor
SomeOtherClass someOtherMock = createMock(SomeOtherClass.class);
expectNew(SomeOtherClass.class).andReturn(someOtherMock);
expect(someOtherMock.do("blabla")).andReturn(...);
Edit: You can use with Mockito with the PowerMockito extensions
http://code.google.com/p/powermock/wiki/MockitoUsage
PowerMockito.whenNew(SomeOtherClass.class)...
I'm pretty sure Mockito does what you are asking, here's some of my test code:
SnapshotManager snapshotManager = mock(SnapshotManager.class);
when(snapshotManager.storeBroadcast("MessageURL1", "B1")).thenReturn(new Distribution("AltMessageURL1", 1));
The syntax is more complex, but the behaviour is the same.
The String literals in the storeBroadcast method do not need to be Strings they can be set to constrain values too.
Plus you have the option to spy on values and to verify the expected methods were called after you injected the instance into your code.

Unit testing class that does not have an output

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.

Is Typemock the only framework that can mock a Linq To SQL Table class?

I am trying to setup unit tests for my Linq To SQL code. My code uses the System.Data.Linq.Table class (generated by the designer).
Because this class is sealed and the constructor is internal it is completely impervious to unit testing frameworks like Rhino Mocks. (Unless you want to alter you code to use the repository pattern, which I would rather not.)
Typemock can (some how) mock this class. (See here for an example.)
However, Typemock is also $800 a license. I don't see my employer springing for that anytime soon.
So here is the question. Are there any other mocking frameworks out there that don't rely on Interfaces to create the mocks?
Edit: Example of code that I need to test:
public class UserDAL : IUserDAL
{
private IDataClassesDataContext _ctx;
public UserDAL()
{
string env = ConfigurationManager.AppSettings["Environment"];
string connectionString = ConfigurationManager
.ConnectionStrings[env].ConnectionString;
_ctx = new DataClassesDataContext(connectionString);
}
public UserDAL(IDataClassesDataContext context)
{
_ctx = context;
}
public List<User> GetUsersByOrganization(int organizationId)
{
IOrderedQueryable<User> vUsers =
(from myUsers in _ctx.Users
where myUsers.Organization == organizationId
orderby myUsers.LastName
select myUsers);
return vUsers.ToList();
}
public bool IsUserInOrganization(User user, int orgainzationID)
{
// Do some Dal Related logic here.
return GetUsersByOrganization(orgainzationID).Contains(user);
}
}
I have shorted this up to make it easier to read. The idea is that I have some code (like IsUserInOrganization that calls another method (like GetUsersByOrganization) that does a Linq query.
I would like to unit test the IsUserInOrganization method. Do do that I would need to mock _ctx.Users which is a Table class (that is sealed and has an internal constructor).
Check out Microsoft Stubs that has the simple premise of:
Replace any .NET method with your own
delegate!
And a more detailed description of it's capabilities (emphasis is mine).
Stubs is a lightweight framework for
test stubs and detours in .NET that is
entirely based on delegates, type
safe, refactorable and source code
generated. Stubs was designed provide
a minimal overhead to the Pex white
box analysis, support the Code
Contracts runtime writer and
encourage the programmatic models
rather than record/replay tests.
Stubs may be used on any .NET method, including non-virtual/static
methods in sealed types.
There are two standard unit testing approaches in this case:
1) Don't test the platform - if the dependency is on a framework class, you don't write tests where that interaction is verified. This typically means you substitute a dependency at test time, but in your case it likely means you inject the table itself.
2) Wrap the platform - if you need to test something that interacts with the platform, then write a wrapper layer for the relevant components
There's also integration and acceptance testing to consider. For both of these cases you would usually simply accept the dependency as it exists in your application.
What precisely are you concerned about testing that you need to directly mock/substitute this class?
Edit:
It seems as if you're looking to avoid rewriting code to be more testable. This is where TypeMock excels, and is the reason why some test advocates think TypeMock can lead to problems. It is, however, the right tool for the job if you absolutely refuse to restructure your code for testability.
Edit #2:
Perhaps I'm being overly obsessive about this, but let's consider a more testable pattern:
Organization()
{
HasUser(name)
}
OrganizationDAL
{
Organization LoadOrganization(id)
}
OrganizationServiceFacade
{
IsUserInOrganization(name, orgid)
{
return OrgDAL.LoadOrganization(id).HasUser(name)
}
}
Organization's natural contains test for a user no longer needs to be platform-dependent, you should be able to inject the datasource. OrganizationDAL is only responsible for loading organizations rather than returning information about organizations (although there are ways to put queries into this layer if necessary). OrganizationServiceFacade is only responsible for providing composed services, which should both satisfy mockability and avoid the need for extra unit tests (it's an Integration or possibly even an Acceptance target) since it's a wrapper class. Depending on how you construct Organizations, you can inject data without relying on a particular notion of how that data works.
You may want to consider using the Repository pattern, basically it's the "wrap the platform" suggestion from Mike. With it you'll be mocking IRepository rather then the DataContext.
http://blogs.microsoft.co.il/blogs/kim/archive/2008/11/14/testable-data-access-with-the-repository-pattern.aspx

Categories