Mocked interface method call does not return as expected

46 views
Skip to first unread message

bkalya...@gmail.com

unread,
Nov 18, 2017, 6:21:56 PM11/18/17
to Spock Framework - User
Hi,

I have an interface as follows:

public interface ServiceHandler
{
   MyDTO<AddressDTO> getAllCopies(String status, Long id);
  ......
}

I have a spring component as follows:

public class Publisher
{
    private final ServiceHandler serviceHandler;
    @Autowired
    public Publisher(ServiceHandler serviceHandler)
    {
       this.serviceHandler = serviceHandler;
    }
   
    @Transactional
    public void publishNow(Long id)
    {
        MyDTO<AddressDTO> mydto = serviceHandler.getAllCopies(Constants.MY_STATUS, id);
        .......
     }
}

My Spock testing groovy class is as follows:

class MySpockTest extends Specification
{
   private ServiceHandler serviceHandler = Mock(ServiceHandler)
   private Publisher publisher
   def setup()
   {
      publisher = new Publisher(serviceHandler)
   }
   def 'My Test'()
   {
      given:
      long id = 1L
      serviceHandler.getAllCopies(_) >> new MyDTO<AddressDTO>() //This should return MyDTO object but, it is returning NULL when I run the test in Publisher class
      when:
      publisher.publishNow(id)
      then:
      1 * serviceHandler.getAllCopies(id)
   }
}

As mentioned in my comment above, instead of returning MyDTO object, it is returning null. Somehow, it is not returning the stubbed value.
Can someone help me what is wrong?

Thank you.


Kostis Kapelonis

unread,
Nov 18, 2017, 7:54:37 PM11/18/17
to spockfr...@googlegroups.com
Hello

Unlike Mockito (which stubs and verifies in different statements),
Spock performs both stubbing and verifying of a mock in a single
statement.

I admit I did not run your code but it should probably work if you
modify the "then:" statement as bellow

1 * serviceHandler.getAllCopies(id) >> new MyDTO<AddressDTO>()

(and of course delete the stubbing method before the "when" block")

Kostis
> --
> You received this message because you are subscribed to the Google Groups
> "Spock Framework - User" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to spockframewor...@googlegroups.com.
> To post to this group, send email to spockfr...@googlegroups.com.
> Visit this group at https://groups.google.com/group/spockframework.
> For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages