lundi 27 avril 2015

Groovy unit testing classes without empty/default constructor

I would like to test a groovy class that does not have an empty constructor. Is there a way to create a mock object or stub object that can be injected into the constructor of the class I want to test?

I would imagine something like that:

 class MyClassToTest {
     public MyClassToTest(SomeHeavyClass x) { ... }
 }

 class SomeHeavyClass {
     public SomeHeavyClass (AnotherHeavyClass y) { ... }
     public methodToTest() { ... }
 }

I want to create a MyClassToTest object with a fake SomeHeavyClass. I'd like to have something like this in my unit test:

def someHeavyClassFake = [methodToTest:{ "return this string in test"}] as SomeHeavyClass
def myClassToTest = new MyClassToTest(someHeavyClassFake)

So I want to pass the someHeavyClassFake dependency that has its methodToTest called which will just return a simple string in test. However this is only possible if my SomeHeavyClass has a default constructor, else the line [methodToTest:{ "return this string in test"}] as SomeHeavyClass will throw a GroovyClassCastException.

What can I do to fake the SomeHeavyClass easily?

Aucun commentaire:

Enregistrer un commentaire