Help, can anyone help out and explain the purpose of the Rhino Mocks 'Record' scope?
I assumed that that the expectation set within the scope would only be verified but it seems as soon as you create the mock object, Rhino Mocks is in 'record mode' so I'm now unsure of the purpose of the Record scope.
Here's an example I have:
private static void SomeTest()
{
MockRepository mockRepository = new MockRepository();
ISomeInterface test = mockRepository.StrictMock<ISomeInterface>();
test.Bar();
using (mockRepository.Record())
{
Expect.Call<string>(test.GetFoo()).Return("Hello");
}
using (mockRepository.Playback())
{
test.GetFoo();
}
}
public interface ISomeInterface
{
string GetFoo();
void Bar();
}
This test would fail because there is an expectation that Bar should be called. Is it because I've created a StrictMock and not Dynamic?
This test will fail because there is no expectation that Bar() would be called, but it was called.
To answer your question, yes, it is because you have a strict mock. If you change to a DynamicMock, it will ignore everything except the expectations that you actually set. I would highly recommend using DynamicMocks wherever possible, as StrictMocks are actually quite brittle and tend to end up being a lot of hassle.
As for Record/Replay, it is not automatically in Record mode if you're using a concrete MockRepository. It's just the nature of the StrictMock that looks for anything being called that was outside of expectations, no matter when.
Related
I'm trying to write a test for a class that has a constructor dependency on Func<T>. In order to complete successfully the function under test needs to create a number of separate objects of type T.
When running in production, AutoFac generates a new T every time factory() is called, however when writing a test using AutoMock it returns the same object when it is called again.
Test case below showing the difference in behaviour when using AutoFac and AutoMock. I'd expect both of these to pass, but the AutoMock one fails.
public class TestClass
{
private readonly Func<TestDep> factory;
public TestClass(Func<TestDep> factory)
{
this.factory = factory;
}
public TestDep Get()
{
return factory();
}
}
public class TestDep
{}
[TestMethod()]
public void TestIt()
{
using var autoMock = AutoMock.GetStrict();
var testClass = autoMock.Create<TestClass>();
var obj1 = testClass.Get();
var obj2 = testClass.Get();
Assert.AreNotEqual(obj1, obj2);
}
[TestMethod()]
public void TestIt2()
{
var builder = new ContainerBuilder();
builder.RegisterSource(new AnyConcreteTypeNotAlreadyRegisteredSource());
var container = builder.Build();
var testClass = container.Resolve<TestClass>();
var obj1 = testClass.Get();
var obj2 = testClass.Get();
Assert.AreNotEqual(obj1, obj2);
}
AutoMock (from the Autofac.Extras.Moq package) is primarily useful for setting up complex mocks. Which is to say, you have a single object with a lot of dependencies and it's really hard to set that object up because it doesn't have a parameterless constructor. Moq doesn't let you set up objects with constructor parameters by default, so having something that fills the gap is useful.
However, the mocks you get from it are treated like any other mock you might get from Moq. When you set up a mock instance with Moq, you're not getting a new one every time unless you also implement the factory logic yourself.
AutoMock is not for mocking Autofac behavior. The Func<T> support where Autofac calls a resolve operation on every call to the Func<T> - that's Autofac, not Moq.
It makes sense for AutoMock to use InstancePerLifetimeScope because, just like setting up mocks with plain Moq, you need to be able to get the mock instance back to configure it and validate against it. It would be much harder if it was new every time.
Obviously there are ways to work around that, and with a non-trivial amount of breaking changes you could probably implement InstancePerDependency semantics in there, but there's really not much value in doing that at this point since that's not really what this is for... and you could always create two different AutoMock instances to get two different mocks.
A much better way to go, in general, is to provide useful abstractions and use Autofac with mocks in the container.
For example, say you have something like...
public class ThingToTest
{
public ThingToTest(PackageSender sender) { /* ... */ }
}
public class PackageSender
{
public PackageSender(AddressChecker checker, DataContext context) { /* ... */ }
}
public class AddressChecker { }
public class DataContext { }
If you're trying to set up ThingToTest, you can see how also setting up a PackageSender is going to be complex, and you'd likely want something like AutoMock to handle that.
However, you can make your life easier by introducing an interface there.
public class ThingToTest
{
public ThingToTest(IPackageSender sender) { /* ... */ }
}
public interface IPackageSender { }
public class PackageSender : IPackageSender { }
By hiding all the complexity behind the interface, you now can mock just IPackageSender using plain Moq (or whatever other mocking framework you like, or even creating a manual stub implementation). You wouldn't even need to include Autofac in the mix because you could mock the dependency directly and pass it in.
Point being, you can design your way into making testing and setup easier, which is why, in the comments on your question, I asked why you were doing things that way (which, at the time of this writing, never did get answered). I would strongly recommend designing things to be easier to test if possible.
I have read through a lot of discussion about #Mock & #InjectMocks and still could not find what are the suitable or necessary cases to use #InjectMocks. In fact, I am not sure about what would happen when we use #InjectMocks.
Consider the following example,
public class User {
private String user_name;
private int user_id;
public User(int user_id) {
this.user_id = user_id;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public int getUser_id() {
return user_id;
}
public void setUser_id(int user_id) {
this.user_id = user_id;
}
}
public interface UserDao {
public List<User> getUserList();
}
public class UserService {
private UserDao userDao;
public UserDao getUserDao() {
return userDao;
}
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
public List<User> getUserList() {
return userDao.getUserList();
}
}
This is my test class
#RunWith(MockitoJUnitRunner.class)
public class UserServiceTest {
private UserService service = new UserService();
#Mock
private UserDao dao;
#Test
public void testGetUserList() {
service.setUserDao(dao);
// mock the return value of the mock object
List<User> mockResult = Arrays.asList(new User(101),new User(102),new User(103));
when(dao.getUserList()).thenReturn(mockResult);
// check return value is same as mocked value
assertEquals(service.getUserList(),mockResult);
// verify the getUserList() function is called
verify(dao).getUserList();
}
}
The test run successfully with no errors.
Consider another approach using #InjectMock annotation.
#RunWith(MockitoJUnitRunner.class)
public class UserServiceTest {
#InjectMocks
private UserService service;
#Mock
private UserDao dao;
#Test
public void testGetUserList() {
service.setUserDao(dao);
// mock the return value of the mock object
List<User> mockResult = Arrays.asList(new User(101),new User(102),new User(103));
when(dao.getUserList()).thenReturn(mockResult);
// check return value is same as mocked value
assertEquals(service.getUserList(),mockResult);
// verify the getUserList() function is called
verify(dao).getUserList();
}
}
This works equally well. So, which way is better? Any best practice?
Btw, I am using Junit 4.8.1 and Mockito 1.9.5
Your actual question can't be answered without you providing further code (the code you are showing does not explain the results you claim to observe).
Regarding the underlying question: you probably should not use #InjectMocks; one of its core problems is: if injecting fails, Mockito does not report an error to you.
In other words: you have passing unit tests, and some internal detail about a field changes ... and your unit tests break; but you have no idea why ... because the mocking framework doesn't tell you that the "initial" step of pushing a mock into the class under test is all of a sudden failing. See here for further reading.
But to be clear here: in the end, this almost a pure style question. People used to #InjectMocks will love it; other people do object it. Meaning: there is no clear evidence whether you should use this concept. Instead: you study the concept, you understand the concept, and then you (and the team working with you) make a conscious decision whether you want to use this annotation, or not.
Edit: I think I get your problem now. The idea of #InjectMocks is to inject a mocked object into some object under test.
But: you are doing that manually in both cases:
service.setUserDao(dao);
Meaning: if injecting works correctly (and there isn't a problem that isn't reported by Mockito) then your example that uses that annotation should also work when you remove that one line. Whereas the testcase that doesn't have #InjectMocks should fail without that line!
In other words: your testcases are both passing because your code does a "manual inject"!
When should we use #InjectMocks?
IHMO : we should not use it.
That favors so many design issues that I would like to add my POV on the question.
Here is relevant information from the javadoc (emphasis is not mine) :
Mark a field on which injection should be performed.
Allows shorthand mock and spy injection.
Minimizes repetitive mock and spy injection.
Mockito will try to inject mocks only either by constructor injection,
setter injection, or property injection in order and as described
below. If any of the following strategy fail, then Mockito won't
report failure; i.e. you will have to provide dependencies yourself.
...
Mockito is not an dependency injection framework,
In two words :
Advantage : you write less code to setup your mock dependencies.
Drawback : no failure if some mocks were not be set in the object under test.
IHMO the advantage hides also another drawback still more serious.
About the advantage :
Mockito uses constructor/setter/reflection to set the mocks in the object under test. The problem is that it is up to you to decide the way to set your fields : mockito will try one after the other way.
The setter way is often very verbose and provides mutability of the dependencies. So developers don't use it frequently. It makes sense.
The constructor way to set the bean dependencies requires to keep a good design with a decent number of dependencies : not more than 4 or 5 in general.
It demands strong design exigencies.
At last, the reflection way is the most easy : few code to write and no mutability of the dependencies.
The reflection way being the simplest from the lambda developer PVO, I saw many teams not aware of the consequences of reflection to specify dependencies and abuse of the reflection way in their Mockito tests but also in their design since finally InjectMocks allows to cope with it in a someway.
You may consider it fine to not finish with a class that declares 30 setters as dependencies or a constructor with 30 arguments but that has also a strong drawback : it favors bad smells such as dependency field hiding and declaration of many dependencies in as field instances of the class. As a result your class is complex, bloat, hard to read, hard to test and error prone to maintain.
The real thing is that in the very most of cases, the right solution is the constructor injection that promotes decent class responsibility and so good maintainability and testability of that.
About the drawback :
Mock injection doesn't work as the dependency injection of IOCs.
The javadoc states itself :
Mockito is not an dependency injection framework,
IOC and DI framework are able and by default consider dependencies as required. So any missing dependency will provoke a fast-fail error at the startup.
It prevents so many headaches and makes you win a precious time.
While Mockito injection will silently ignore the mocks that were not managed to be injected. It is so up to you to guess the error cause.
Finding the issue cause is sometimes complex because you don't have any clue from Mockito and that all is done by reflection by Mockito.
Using #InjectMocks injects the mocked objects as dependencies to the created object(The object marked by #InjectMocks). Creating an object using constructor will defy the purpose since the mocked objects are not injected and hence all the external calls from SUT takes place on concrete objects.Try to avoid creating SUT object by constructor call.
I am new to both libraries and before committing to their usage on a large project I need clarification on my options for low-code effort automocking in my unit tests.
After spending some time on Google I have concluded that, unlike some other IOC/Mocking product pairings, a ready-made plugin library is not available for LightInject+Nsubstitute to simplify the declaration of do-nothing default mocks in the arrange stage of a unit test.
I have read the LightInject docs on how to override a LightInject container with a temporary enhanced mock object just for the scope of a unit test but what about all the do-nothing default isolation mocks that a unit test might touch. Is there a way to automate their creation within the LightInject container?
The internal IOC container behaviour I am looking for is:
public class LightInject.ServiceContainer
{
..
public T GetInstance<T)
{
if (( this.RegisteredInterfaces.Any( i => i.Itype == T ) == false )
&& ( this.TemporaryUnitTestOverrides.Any( i => i.Itype == T ) == false ))
&& ( /* this container is configured with an automocking delegate */ ))
return autoMockCreatorDelegate<T>.Invoke();
}
It seems like LightInject's IProxy and Interceptors provide some internal mock object building blocks but the Nsubstitute library is full featured in comparison.
Clarification on what I mean by default do nothing mock and an enhanced mock.
// default do nothing mock
var calculator = Substitute.For<ICalculator>();
// Enhanced mock that will return 3 for .Add(1,2)
var calculator = Substitute.For<ICalculator>();
calculator.Add(1, 2).Returns(3);
Obviously the second enhanced type of mock will need to be crafted locally per unit test.
I am the author of LightInject and would really like to help you out.
Let me look into this and get back to you. In the meanwhile you might want to check out this library at
LightInject.AutopMoq which is a third party contribution to the LightInject container. It uses Moq instead of NSubstitute, but the general concept should be similar to what you are asking for.
That being said, I did some work a while ago that simplifies automocking even further and will take a look at it it and see how that can be integrated with NSubstitute.
Edit
This is a super simple automocking implementation that works with any "substitute" framework.
using System.Diagnostics;
using LightInject;
using NSubstitute;
public interface IFoo { }
class Program
{
static void Main(string[] args)
{
var serviceContainer = new ServiceContainer();
serviceContainer.RegisterFallback((type, s) => true, request => CreateMock(request.ServiceType));
var foo = serviceContainer.GetInstance<IFoo>();
Debug.Assert(foo is IFoo);
}
private static object CreateMock(Type serviceType)
{
return Substitute.For(new Type[] { serviceType }, null);
}
}
Best regards
Bernhard Richter
Some feedback as promised in my comment to the accepted answer. I applied the suggestion from the author of LightInject with success in some simple unit tests.
After getting the basics working I decided to hide the Ioc service mocking setup code in a base class plus something I have called a MockingContext, the end result is cleaner lighter unit test code. The mocking context class also ensures that foreach Nsubstitute configured mock type passed to the Ioc service as a short term automock override, there is a matching LightInjet.Service.EndMocking( T ) call. This removes the danger that configured mocks might pollute the auto mocking assumptions of a following unit test.
In the example ClassC depends on IFooA and IFooB (no constructor injection). For the unit test below, IFooA is auto mocked by LightInject without explicit code whereas IFooB is configured via an Nsubstitute call and also passed to LightInject in the MockingContext.Add<>() method.
[TestClass]
public class UnitTest1 : AutoMocking
{
[TestMethod]
public void Test_1()
{
using (var mc = MockingContext)
{
// No need to mention IFooA here, LightInject will auto mock
// any interface not previously declared to it.
// Given
var mockB = mc.Add<IFooB>();
mockB.MethodY().Returns("Mock Value OOO");
var sut = new ClassC();
// When
var testResult = sut.MethodZ();
// Then
Assert.AreEqual(testResult, "MethodZ() received=Mock Value OOO");
}
}
Suppose the next class
interface Thing {
void doSomething();
}
public class Test {
public void doWork() {
//Do smart things here
...
doSomethingToThing(index);
// calls to doSomethingToThing might happen in various places across the class.
}
private Thing getThing(int index) {
//find the correct thing
...
return new ThingImpl();
}
private void doSomethingToThing(int index) {
getThing(index).doSomething();
}
}
Intelli-J is telling me that I'm breaking the law of demeter since DoSomethingToThing is using the result of a function and supposedly you can only invoke methods of fields, parameters or the object itself.
Do I really have to do something like this:
public class Test {
//Previous methods
...
private void doSomething(Thing thing) {
thing.doSomething();
}
private void doSomethingToThing(int index) {
doSomething(getThing(index));
}
}
I find that cumbersome. I think the law of demeter is so that one class doesn't know the interior of ANOTHER class, but getThing() is of the same class!
Is this really breaking the law of demeter? is this really improving design?
Thank you.
Technically, this is breaking the Demeter's laws. Though I would contest that private functions should be considered for LoD-F, as supposedly they are not accessible from outside. At the same time, it's not really breaking Demeter's laws, if 'thing' is owned by Test. But in Java, the only way to get to thing may be through a getter, which takes this back to that technicality (no clear separation between getter and action methods).
I would say, do this:
public class Test {
private Thing getThing(int index) {
//find the thing
return thing;
}
private void DoSomethingToThing(Thing thing) {
thing.doSomething();
}
private void DoSomethingToThing(int index) {
DoSomethingToThing(getThing(index));
}
}
Or, probably better, have the caller use thing directly. Which is possible if Test's function is to produce or expose things, rather than being the intermediary to manipulate thing.
IntelliJ is not detecting object instantiation correctly.
Wikipedia (what IDEA links to) describes that you can call objects created in the current context.
That's what I do, but still I get the warning on getMajor():
Version version = Loader.readVersion(inputStream); // Instantiates a new Version
if (version.getMajor() != 2)
throw new IOException("Only major version 2 is supported");
IDEA's inspection offers an option to ignore calls to 'library' methods. In my case, Loader.readVersion() is a library method, however it's located inside the current project (the project must be self-supporting). IDEA thinks it's not a library method.
Since the mechanism of this inspection is inadequate/incomplete/naive (like with MANY of IDEA's inspections btw), the only solution is disabling it and attempt to avoid these situations manually.
I have a class that has two methods. One method needs to call the other method and in my test I want to assert that it was called.
public class Tasks : ITasks
{
public void MethodOne()
{
MethodTwo(1);
}
public int MethodTwo(int i)
{
return i + 1;
}
}
I want to mock Tasks and do something like tasks.AssertWasCalled(x => x.MethodTwo(1)). Must MethodTwo be virtual?
The concept you're looking for is partial mocks (this shows old syntax, but I don't remember the new one off the top of my head). You should read up on it. Essentially you create the mock on Tasks (not ITasks) and tell it to mock out only MethodTwo (which needs to be virtual).
However...you might want to reconsider your design. What is ITasks? What is the role? Are they different actual tasks? Is there any reason why you would want them in the same class? My understanding is that partial mocks is only included for when you need to test legacy components - I've never found a use for it.
Of course my thinking at that time was flawed. I should be mocking ITasks, not the implementation (Tasks):
ITasks tasks = MockRepository.GenerateMock<ITasks>();
tasks.AssertWasCalled(x => x.MethodTwo(Arg<int>.Is.Equal(1)));