mardi 23 octobre 2018

Mock parent class behaviour (protected method) when testing child

I am using Spock to unit test project I've just joined. There is a problem however with writing tests for Java code.

class Parent {
   private SomeObject obj;
   public void getSomeObject() {return obj;}
   public void setSomeObject(final SomeObject obj) {this.obj = obj}
}

// THIS IS THE CLASS I AM TESTING
class Child extends Parent {
   public String doSth() {
       getSomeObject().dosomethingontheobject()  // This line causes problem
   }    
}

This is the test method that I am using

def 'test'() {
   given:
   SomeObject obj = Mock()
   obj.dosomethingontheobject() >> [somethin1, somethin2]

   Child child = new Child()
   child.setSomeObject(obj)

   when:
   child.doSth()

   then:
   1 * obj.dosomethingontheobject()
}

When running I am getting 'too few invocations' error for calling 'dosomethingonobject()' method.

Aucun commentaire:

Enregistrer un commentaire