Re: How to mock a Java Future?

2,914 views
Skip to first unread message

Peter Niederwieser

unread,
Aug 16, 2012, 3:19:30 PM8/16/12
to spockfr...@googlegroups.com
Mocking and stubbing has to be done together. You can't split up "eS.submit" into two parts. Search the mailing list for more information (this has been discussed many times already).

Cheers,
Peter

On Aug 16, 2012, at 7:57 AM, ashish <ashi...@gmail.com> wrote:

> Hi,
> I have a following class that I need to test:
>
> public class Abc {
> private ExecutorService eS;
>
> public Abc() {
> eS = Executors.newFixedThreadPool(4);
> }
>
> public boolean process(Request request) {
> Callable c = new SomeCallable(request);
> Future<Boolean> future = eS.submit (c);
> try {
> return future.get().booleanValue();
> } catch (Exception e) {}
> return false;
> }
> }
>
> Now in my Speciication I have something like:
>
> class AbcSpec extends Specification {
> Abc abc
> ExecutorService eS
> Future<Boolean> f
>
> def setup() {
> eS = Mock(ExecutorService)
> f = (Future<Boolean>) Mock (Future)
> f.get() >> Boolean.TRUE
> eS.submit(_) >> f
>
> abc = new Abc();
> }
>
> def "should call submit"() {
> given:
> abc.eS = eS
> when:
> abc.process(request)
> then:
> 1 * eS.submit(_)
> }
> }
>
> Though I am expecting the eS.submit() to return a Mocked Future I get a NPE in the code where it does return future.get().booleanValue() because future returned is null.
>
> How to mock such a code? btw, had this been a Runnable the test works.
>
> Thanks!
>
> --
> You received this message because you are subscribed to the Google Groups "Spock Framework - User" group.
> To view this discussion on the web visit https://groups.google.com/d/msg/spockframework/-/1emHODC-hjcJ.
> To post to this group, send email to spockfr...@googlegroups.com.
> To unsubscribe from this group, send email to spockframewor...@googlegroups.com.
> For more options, visit this group at http://groups.google.com/group/spockframework?hl=en.
>

Reply all
Reply to author
Forward
0 new messages