OCMClassMock and OCMStrictClassMock - ios

I am new in OCMock 3, I see there are two methods:
OCMClassMock(cls): creates a new nice class mock object
OCMStrictClassMock(cls): creates a class mock object
I read the document, but I feel still confused & have two questions:
What exactly the difference between OCMClassMock(cls) and OCMStrictClassMock(cls) ?
When should I use OCMClassMock(cls) and when should I use OCMStrictClassMock(cls)?
====UPDATE====
Can I understand as OCMClassMock(cls) is partial mock that the real implementation still run when call method on it and OCMStrictClassMock(cls) is a full mock like a skeleton without real implementation?

Can I understand as OCMClassMock(cls) is partial mock that the real
implementation still run when call method on it
This describes OCMPartialMock.
OCMStrictClassMock(cls) is a full mock like a skeleton without real
implementation?
This is an accurate general description of OCMClassMock.
From the reference you linked:
[OCMStrictClassMock] Creates a mock object in strict mode. By
default mocks are nice, they return nil (or the correct default value
for the return type) for whatever method is called. In contrast,
strict mocks raise an exception when they receive a method that was
not explicitly expected.
So as you said, OCMClassMock is like a skeleton of an instance where you only stub the methods that you need to use. The difference between OCMClassMock and OCMStrictClassMock is that the former will simply return nil for a method that you haven't explicitly stubbed, whereas the latter will throw an exception if you call a method on it that you haven't explicitly stubbed.

Related

in unit test, set mocked value to an argument (pass-by-reference)

I have a method:
-(void)startTaskForResult:(long long*)result {
...
}
The function I want to unit test invoke above function:
-(void)doWork {
long long result = 0;
[self startTaskForResult:&result];
}
I am using OCMock library to do unit tests. In my test case, I want to set the result argument to an mocked value e.g. 100 without care about the actual implementation of -(void)startTaskForResult:(long long*)result.
I tried the following way:
-(void)testDoWork{
// try to set 100 to argument 'result'
OCMStub([classToTest startTaskForResult:[OCMArg setToValue:OCMOCK_VALUE((long long){100})]]);
// run the function, but it doesn't use mocked value 100 for argument 'result'
[classToTest doWork];
...
}
But, when I run my test, it does't use the mocked value 100 for argument result. What is the right way to set mocked value to argument in my case then?
Few points to answer your question:
Code for your problem:
- (void)testDoWork
{
id mock = OCMPartialMock(classToTest)
OCMStub([mock startTaskForResult:[OCMArg setToValue:OCMOCK_VALUE((long long){100})]]).andForwardToRealObject;
// set your expectation here
[classToTest doWork];
}
To solve your particular problem:
Your object should be partial mock
Your method should be stubbed (you did it)
Your stub should be forwarded to real object (i assume you need method startTaskForResult: implementation to be called)
However, you face the problems because you are using wrong approach to test;
There're 3 most common strategies to write unit tests:
Arrange-Act-Assert used to test methods
Given-When-Then used to test functions
Setup-Record-Verify used to test side effects. This usually requires mocking.
So:
If you want to test that startTaskForResult: returns particular value - you should call just that and expect return value (not your case, method return type is void)
If method changes the state of object - you should expect that state change, like property value or so
If calling of doWork has a side effect of calling startTaskForResult:, you should stub it and expect it's call, almost like i've written in code above. However (!!!), however you shouldn't expect things like this. This is not a kind of behaviour that has much sense to test, because it's internal class implementation details. One possible case, when both methods are public and it's explicitly stated in class contract, that one method should call another with some preliminary setup. In this case you expect method call with some state / arguments.
To have your application code testable, you require continuously refactoring your code. Some code is untestable, it's probably better to adopt application code rather then try to cover it with tests anyway. You lose the initial goal of tests - refactoring safety and low cost of making changes.

RSpec stubbing a complex Rails result to test one nested field

I'm using RSpec's stubbing functionality to stub a where() call on an object:
allow(ActiveRecordObject).to_receive(:where).and_return(result)
This works great when the expected result is simple, such as an instance of the ActiveRecordObject with a field set to a certain value.
However, the result I want to test is more complex. I'm intending to test a value set on another ActiveRecordObject that is nested three deep through Rails hasMany functionality and this is more tricky. For example, I'd like ...
expect(result[:child_object][:test_target][:field]).to eq(value)
... to work as a test after the function that I'm testing is called.
The way I've attempted and so far failed to achieve this is by copying the structure of the object so the result is a considerably more complex.
What I'd like to do is stub the actual call (or value, if a call isn't really made) to test_target so when the call is made a much more simple stub is hit. This seems to me to be better as it creates less brittle, easier to understand code.
I've also tried stubbing a where() method on the class TestTarget.
What is the correct way to configure values in linked ActiveRecord objects in RSpec so that when the parent object is called the resulting structure contains a value hard-coded for test.
Also, is this possible without using Factory Girl (tech leads at work have decided that we want to move away from using FactoryGirl)

Why is mocking with DI better than mocking objects in objective-c?

this blog article says that:
While there are sometimes sensible ways to mock out objects without DI
(typically by mocking out class methods, as seen in the OCMock example
above), it’s often flat out not possible. Even when it is possible,
the complexity of the test setup might outweigh the benefits. If
you’re using dependency injection consistently, you’ll find writing
tests using stubs and mocks will be much easier.
but it doesn't explain why. What are possible scenarios where DI (injecting an id object conforming to protocol) will serve better for mocking in Objective-C, than simple OCMockito:
[given([mockArray objectAtIndex:0]) willReturn:#"first"];
[verifyCount(mockArray, times(1)) objectAtIndex:];
?
I've noticed that it is easier to create a separate class for test target when the original class do some async stuff.
Let assume you write a test for UIViewController which has a LoginSystem dependency which uses AFNetworking to do a request to the API. LoginSystem takes a block argument as a callback. (UIViewController->LoginSystem->AFNetworking).
If you make a mock of LoginSystem probably you will end with problems how to fire a callback block to test your UIViewController behaviour on success/failure. When I tried that I ended with MKTArgumentCaptor to retrieve a block argument and then I had to invoke it inside a test file.
On the other hand, if you create a separate class for LoginSystem (let call it LoginSystemStub which extends from LoginSystem) you are able to "mock" a behaviour in 3 lines of code and outside the test file. We should also keep our test file clean and readable.
Another case is that verify() doesn't work with checking asynchronous behaviour. It is much more easier to call expect(smth2).will.equal(smth)
EDIT:
Pointers to NSError (NSError**) also don't work well with verify() and it's better to create a stub :D
Imagine you are trying to test a more complex behavior of an object interacting with one of its child objects. To make certain that the parent object is operating correctly, you have to mock all the methods of the child object and even potentially track its changing state.
But if you do that, you just wrote an entirely new object in a confusing and convoluted way. It would have been simpler to write an entirely new object and tell the parent to use that.
With DI you inject your model at runtime, it's not bound in your classes but only in the configuration.
When you want to mock you just create a mock model and inject that instead of your real data. Besides the model, you changed your implementation in a single line.
See here for a hands on example or here for the idea behind it.
Disclaimer: Of course you can mock other stuff than the model, but that's probably the most common use-case.
The answer is: It's not better. It's only better if you need some super custom behavior.
The best thing about it is that you don't have to create an interface/protocol for every class you inject and you can limit to DI the modules you really need to inject making your code cleaner and more YAGNI.
It applies to any dynamic language, or language with reflection. Creating so much clutter just for the sake of Unit-Tests struck me as a bad idea.

Why are Controller Constructors fired before the Initialize method

I have a base Controller ApplicationController that needs to grab the URL Host and do some processing before the child controllers are fired. Since controller constructors are fired before RequestContext is initialized I have to override Initialize method to do my processing.
ApplicationController:
Protected Overrides Sub Initialize(ByVal requestContext As System.Web.Routing.RequestContext)
MyBase.Initialize(requestContext)
Dim host as String
host = Request.Url.Host.ToString
End Sub
What is the logic behind having Controller Constructors fire before the Initialize method?
Also what are the rules to what should be placed in the Initialize Method.
Assuming that constructors are the first instance method ever to be fired in a .NET class, that shouldn't come as a surprise and is not really something MVC specific. It's more how the .NET framework works.
The MVC framework needs to first instantiate a controller and then initialize it => it calls the constructor first. And because performing lots of code that could potentially might throw exceptions, etc... is not always best to be put in a constructor => the presence of the Initialize method. As far as this method is concerned I must admit that I have written lots of ASP.NET MVC code and never had to use it. Action filters always seemed like a better alternative.
So to answer your question:
Also what are the rules to what should be placed in the Initialize Method.
I've never ever put any code and never ever need to override this method. I've always preferred using action filters because this way I am no longer in the obligation of deriving from a common base controller (not that this is a problem).
Sometimes, maybe you would want your request to initialize your variables, so in this case you should use the Initialize method.
For example, if you want to initialize some variables in a different way when the request is local or not, etc.

Prefer Dependency-Injection over Partial Mocking?

I know this SO question, but it deals with the subject in more general terms.
Should I prefer using partial Mocks over Dependency Injection? My question is based on the following quote from OCMock:
id aMock = [OCMockObject partialMockForObject:anObject]
Creates a mock object that can be used
in the same way as anObject. When a
method that is not stubbed is invoked
it will be forwarded anObject. When a
stubbed method is invoked using a
reference to anObject, rather than the
mock, it will still be handled by the
mock.
This means I could stub my (property-)dependecies away using a partial mock instead of injecting them in the constructor (or via setter injection).
You should design your API so that it makes sense as a general-purpose API, not particularly to support unit testing or dynamic mocks.
The pattern you suggest is simply a variation of the Template Method design pattern, except that the method is a property. If you think that, in general, it makes sense to implement your dependency access as virtual properties, then you can use the technique you describe. This is a well-known unit testing technique called extract and override.
However, I would be vary of doing this for a number of other reasons.
Even if you can override the dependency, the default may drag in references to the 'real', intended depdendency creating a tighter coupling than you may want.
If you forget to extract and override, the default dependency is used, and you may not want that. Sometimes it's better to be explicit about the intended usage.

Resources