[TIP] mock-ing java classes in Jython?

Michael Foord fuzzyman at voidspace.org.uk
Sun Jul 31 09:13:15 PDT 2011


On 31 Jul 2011, at 11:23, Fredrik Håård wrote:
> 
> Hi all (and thanks for the pizza! =),
> 
> I'd like to set up a test suite for an embedded J2ME application. Most of the code is cleanly separated from the platform since it runs on multiple platforms, and I wanted to use Jython to replace the platform-specific parts and run both unit and scenario testing on the common parts. 
> 
> However, naive replacement of the class definitions does not seem to work, and trying to use mock to patch a java class like this:
> 
> with mock.patch('my.device.DeviceHandler') as devicehandler:
> 
> i get:
> 
> AttributeError: 'javapackage' object has no attribute 'DeviceHandler'
>     
> Is it possible to get the behavior I want?


I don't use python, but I assume that in Jython you can't replace arbitrary attributes on modules written in Java - just as you can't replace arbitrary attributes on modules written in C on CPython.

A way round this would be to import 'DeviceHandler' into your module (instead of accessing it as 'my.device.DeviceHandler' just use DeviceHandler). Then you can just patch 'DeviceHandler' in the module you use it rather than having to patch it on the package that contains it.

All the best,

Michael Foord

--
http://www.voidspace.org.uk/


May you do good and not evil
May you find forgiveness for yourself and forgive others
May you share freely, never taking more than you give.
-- the sqlite blessing 
http://www.sqlite.org/different.html









More information about the testing-in-python mailing list