How to mock a C-function using OCMock - objective-c

How do I mock a custom c-lib function using ocmock? Couldn't find anything on google, and any method stubbing functions from OCMock doesn't work

One solution could be to encapsulate that functions inside an static class and mock it. In this way you can test the functions itself and mock his usage (using the static class).

You cannot mock C functions with OCMock. You will need to use another framework.

Related

How to mock a new object using mockk

I'm trying to write unit tests using mockk.
I'm trying to figure out how to mock a new instance of an object.
For example, using PowerMockito we would write:
PowerMockito.whenNew(Dog::class.java).withArguments("beagle").thenReturn(mockDog)
If the expected result of my test is mockDog, I want to be able to assert that it equals my actualResult:
assertEquals(mockDog, actualResult)
How would I accomplish this using mockk?
Thanks in advance.
Using mockkConstructor(Dog::class) you can mock constructors in MockK. This will apply to all constructors for a given class, there is no way to distinguish between them.
The mocked class instance can be obtained by using anyConstructed<Dog>(). You can use that to add any stubbing and verification you need, such as:
every { anyConstructed<Dog>().bark() } just Runs
MockK is a lib for unit testing your code. Don't use it for mocking constructor. You can use PowerMock for mocking constructor if you really need to mock constructor.

How to test class methods using OCMock

I wonder if there is a way using OCMock can invoke a class method twice separately as if the app runs two times, but in fact, only once.
I want to test a class method. Due to some static variables inside the method, the method will keep its behavior all the time once it's called. Thus I can't test different behaviors at one time.
And of course, I can't add anything else to the class if the purpose is only for testing.
There is not a way to alter statically declared variables with OCMock without exposing them via Objective-C methods. You say "of course" you can't add anything to the class just for testing purpose, but this is not universally accepted. There is a an entire school of thought that believes your code itself should be designed to be tested.
- (NSInteger)someStatic
{
static NSInteger _someStatic = 42;
return _someStatic;
}
If you used a pattern like that that (for example, there may be better ones) you could mock your static. While this will add a method call anywhere the static is used, you may find it more important to have comprehensive testing.
OCMock version 2.1 has support for mocking class methods:
OCMock 2.1 released
15 March 2013
New release (2.1) which adds support for stubbing class methods and includes many contributed bug fixes. This release is compatible with Xcode 4.5/4.6.
The "Features" page on their website give some examples on how to mock a class method:
Class methods
[[[mock stub] andReturn:aValue] someClassMethod]
Tells the mock object that when someClassMethod is called on the class for which the mock object was created it should return aValue. This is the same syntax that is used to stub instance methods.
In cases where a class method should be stubbed but the class also has an instance method with the same name as the class method, the intent to mock the class method must be made explicit:
[[[[mock stub] classMethod] andReturn:aValue] aMethod]
The class can be returned to its original state, i.e. all stubs will be removed:
[mock stopMocking]
This is only necessary if the original state must be restored before the end of the test. The mock automatically calls stopMocking during its own deallocation.
Note: If the mock object that added a stubbed class method is not deallocated the stubbed method will persist across tests. If multiple mock objects manipulate the same class at the same time the behaviour is undefined.

Rhino mock a singleton class

I want to test my controller that depends on a hardware C# class, not an interface.
It's configured as a singleton and I just can't figure out how to RhinoMock it.
The hardware metadata (example) for the dependent class:
namespace Hardware.Client.Api
{
public class CHardwareManager
{
public static CHardwareManager GetInstance();
public string Connect(string clientId);
}
}
and in my code I want this something like this to return true, else I get an exception
if( !CHardwareManager.GetInstance().Connect("foo") )
I mock it using:
CHardwareManager mockHardwareMgr MockRepository.GenerateMock<CHardwareManager>();
But the Connect needs a GetInstance and the only combination I can get to "compile" is
mockHardwareMgr.Expect (x => x.Connected ).Return(true).Repeat.Any();
but it doesn't correctly mock, it throws an exception
but this complains about typing the GetInstance
mockHardwareMgr.Expect (x => x.GetInstance().Connected).Return(true).Repeat.Any();
So my problem - I think - is mocking a singleton. Then I have no idea how to make my controller use this mock since I don't pass the mock into the controller. It's a resource and namespace.
90% of my work requires external components I need to mock, most times I don't write the classes or interfaces, and I'm struggling to get them mocked and my code tested.
Any pointers would be welcome.
Thanks in advance (yes, I've been searching through SO and have not seen something like this. But then, maybe my search was not good.
The usual way to avoid problems with mocking external components is not to use them directly in your code. Instead, define an anti-corruption layer (usually through an interface that looks like your external component) and test your code using mocked implementation of this interface. After all, you're testing your own code, not the external one.
Even better way is to adjust this interface to your needs so it only exposes stuff that you actually need, not the whole API the external component provides (so it's actually an Adapter pattern).
External components are tested using different approaches: system testing, in which case you don't really mock them, you use the actual implementation.
Usually when you try to get Rhino Mocks to do something which feels unnatural and Rhino growls, this is a good sign that your approach is not the right one. Almost everything can be done using simple interface mocking.
As Igor said RhinoMocks (and most other free mocking frameworks, e.g. Moq) can only mock interfaces.
For mocking classes try (and pay) TypeMock.
For mocking singletons see my answer to:
How to Mock a Static Singleton?
Yes, I'm somewhat undermining the common understanding of what's deemed testable and thus "good" code. However I'm starting to resent answers like "You're doing it wrong. Make everything anew." for those answers don't solve the problem at hand.
No, this is not pointing at Igor, but at many others in similar threads, who answered "Singletons are unmockable. (Make everything anew.)".

Asserting a method invocation on one of several injected types

We use RhinoMocks. I have a type into whose constructor 9 types are injected. I'd like a way of automocking the type, but being able to detect a particular method invocation on one of the injected objects (i.e. I only care about a single method invocation on one of the injected objects).
Is this possible, or do I have to manually inject all the mock objects into the constructor?
I haven't seen any frameworks that would auto-create these mocks for you. You can do it in your [SetUp] method, so at least the tests will not be cluttered with boilerplate code.
I need to check out http://autofixture.codeplex.com/. Its not really container specific, there is an extension for rhino mocks. Disclaimer: I haven't tried autofixture yet.

Jython: is there a clean way to implement a Java interfaces with function references?

I know that I can implement a Java interface with Jython like this:
class MyListener (Listener):
def foo(self, event):
print(str(event))
Python has first-class functions so that seems like an overkill - especially for interfaces with one method. Is there a way to just pass a lambda or function which implements a single method in an interface instead?
As of Jython 2.5.2 (beta 2), Jython functions work as implementations of single method Java interfaces. From http://www.zyasoft.com/pythoneering/2010/09/jython-2.5.2-beta-2-is-released/ :
Python functions can be directly passed to Java methods that take a single method interface (such as Callable or Runnable). This means you can now pass a callback function, usually a closure, instead wrapping it in a class implementing that interface. Tobias Ivarsson implemented this feature.
According to online examples, it is possible for the AWT/Swing Event interface. Simply create a closure with the correct arguments, pass it on and Jython should do the rest. Unfortunately I did not succeed in replicating this behavior for self declared interfaces as I always get a "TypeError: arg can't be coerced" exception.
I, too, would really like to know if it's possible and if so, what I'm doing wrong.