Monkey Patching in D

QAston qaston at gmail.com
Wed Jun 5 22:45:03 PDT 2013


On Wednesday, 5 June 2013 at 13:19:33 UTC, Peter Lundgren wrote:
> On Wednesday, 5 June 2013 at 07:17:50 UTC, Jacob Carlborg wrote:
>> I would suggestion using some kind of wrapper instead of doing 
>> true monkey patching. Example:
>>
>> class Wrapper
>> {
>>    private Object o;
>>    this (Object o) { this.o = o; }
>>
>>    auto opDispatch (string name, Args ...) (Args args)
>>    {
>>        // Use this function to "catch" all calls and forward 
>> as necessary to "o"
>>    }
>> }
>>
>> http://dlang.org/operatoroverloading.html#Dispatch
>
> That's a reasonable option too. I think I'd rather use deject.
>
> The problem I'm trying to solve (and maybe this isn't as 
> important as I think) is that DMocks or deject + DMocks only 
> works on a subset of the language. I can't mock out free 
> function calls, private or final methods, or functions on 
> structs or unions (can I inject mocked structs using deject?).
>
> What do I do when I want to mock out std.stdio or std.random?

Making mocks work with statical world of D could definitely be 
done - the language has many useful tools like alias or mixins to 
do that. I think that substitution here may be a problem. It'd 
probably be required to use aliases instead of bare types in user 
code, so types could be fully substituted.  Mocking statically 
linked methods is a similar problem - consider:
MyType a = new Mocker().mock!(MyType );
a.finalMethod()
will call MyType.finalMethod, not Mock!MyType.finalMethod. Using 
aliases for defining types is a sollution but it requires changes 
to user code. Maybe deject has a sollution to this problem.


More information about the Digitalmars-d mailing list