Muki-SkyWalker / specs

Automatically exported from code.google.com/p/specs
Other
0 stars 0 forks source link

Mock returns/stubReturns Type is Incompatible with Wildcards #92

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
Consider the following Java interface:

public interface Foo {
    public java.util.List<? extends Bar> baz();
}

I can attempt to mock this interface in the following way:

val ls: java.util.List[Bar] = new ArrayList[Bar]

val m = mock[Foo]
m.baz returns ls     // error!

Unfortunately, this code will fail to compile.  It seems that the Scala
compiler believes that baz() expects something of type java.util.List[_ <:
Bar], but it got something of type java.util.List[_ <: Bar].  Yeah, I don't
get it either...

I've tried a whole host of different ways of getting around this error in
my Scala code, from turning the existential type into an inferred method
type parameter to explicitly casting to an existential type (which doesn't
work, btw).  I can't find any way to get around the problem.  I can't
change the Java API.

It is possible that this issue can be fixed in the `returns` type
signature, but I'm honestly not sure.  I find it hard to believe that Scala
can't handle this case in some way.

For the record, I'm using EasyMock with Specs 1.6.0.

Original issue reported on code.google.com by djspie...@gmail.com on 21 Sep 2009 at 10:37

GoogleCodeExporter commented 9 years ago
Hi Daniel,

I got it working with the following:

  "An easymock mock with a java interface" should {
    "work with a java method returning a genericized list" in {
      val ls: java.util.List[Bar] = new java.util.ArrayList[Bar]
      ls.add(new Bar(1))
      val m = mock[Foo]
      m.getBars.asInstanceOf[java.util.List[Bar]] returns ls 
      replay(m)
      m.getBars.get(0).i must_== 1
    }
  }

and 

public interface Foo {
  public java.util.List<? extends Bar> getBars();
}

public class Bar {
  public int i;
  public Bar(int i) {
    this.i = i;
  }
}

Did you try to force the cast to List<Bar> like this, or is it not possible in 
your 
specific case?

Original comment by etorrebo...@gmail.com on 22 Sep 2009 at 10:40

GoogleCodeExporter commented 9 years ago
I'm embarrassed to admit that I didn't think to try that.  At least to me, it 
has
always seemed a little strange that mock frameworks stub methods by first 
*calling*
that method and then asserting what the return value *should* have been.  Just 
way
too weird...

Thanks for the assist!

Original comment by djspie...@gmail.com on 22 Sep 2009 at 2:49