简体   繁体   中英

How I can stub abstract java class with protected abstract methods via ScalaMock?

I'm trying to stub abstract java.nio.channels.ServerSocketChannel class but got

Error:(15, 18) object creation impossible, since:
it has 2 unimplemented members.
/** As seen from <$anon: java.nio.channels.ServerSocketChannel>, the missing signatures are as follows.
 *  For convenience, these are usable as stub implementations.
 */
  protected[package spi] def implCloseSelectableChannel(): Unit = ???
  protected[package spi] def implConfigureBlocking(x$1: Boolean): Unit = ???
    socket = stub[ServerSocketChannel]

Of course I can override these methods in test subclass but maybe there is a more elegant solution?

Macro Mocks are subclasses of the type to mock. So they abide by the same restrictions as regular class hierarchies in Scala. Instead of depending on the abstract class directly, could you use an interface, eg NetworkChannel and mock that ?

example for widening the visibility of a method:

package java.nio.channels;

abstract class ServerSocketChannelSub extends ServerSocketChannel {
  def implCloseSelectableChannel(): Unit
  def implConfigureBlocking(x: Boolean): Unit
}

then in your test

val socketChan = mock[ServerSocketChannelSub]

All side-effects of constructing an instance of this subclass will also apply on each mock, there is no way around this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM