jeudi 27 avril 2017

Why might a Mockito test pass for any expected number of invocations?

I'm writing the following test using specs2 and Mockito.

class HttpServiceSpec extends Specification with Mockito {
"not accept self-signed certificates if acceptSelfSignedCerts is false" in {
  val httpClientBuilder = mock[HttpClientBuilder]
  HttpService.build(
    httpClientBuilder,
    httpConnectionManager,
    httpRoutePlanner,
    idleConnectionManager,
    _ => sslConnectionSocketFactory,
    sslContextBuilder,
    trustSelfSignedStrategy
  )(0, 0, acceptSelfSignedCerts = false)

  there was no(httpClientBuilder).setSSLSocketFactory(sslConnectionSocketFactory)
}
}

Here is the relevant code under test:

object HttpService {
  def build(
    httpClientBuilder: HttpClientBuilder,
    httpConnectionManager: PoolingHttpClientConnectionManager,
    httpRoutePlanner: HttpRoutePlanner,
    idleConnectionManager: IdleConnectionManager,
    makeSSLConnectionSocketFactory: SSLContext => SSLConnectionSocketFactory,
    sslContextBuilder: SSLContextBuilder,
    trustSelfSignedStrategy: TrustSelfSignedStrategy
  )(maxConnections: Int, maxConnectionsPerRoute: Int, acceptSelfSignedCerts: Boolean): HttpService = {
    httpClientBuilder.setRoutePlanner(httpRoutePlanner)

    if (maxConnections > 1) {
      httpConnectionManager.setMaxTotal(maxConnections)
      httpConnectionManager.setDefaultMaxPerRoute(maxConnectionsPerRoute)
      idleConnectionManager.fireEvictionThread()
      httpClientBuilder.setConnectionManager(httpConnectionManager)
    }

    if (acceptSelfSignedCerts) {
      val sslContext: SSLContext = sslContextBuilder.loadTrustMaterial(trustSelfSignedStrategy).build()
      httpClientBuilder.setSSLSocketFactory(makeSSLConnectionSocketFactory(sslContext))
    }

    val client = httpClientBuilder.build()

    new HttpService(client, Some(idleConnectionManager))
  }
}

If I change the last line of the test to either of the following the test will pass:

  there was one(httpClientBuilder).setSSLSocketFactory(sslConnectionSocketFactory)
  there was no(httpClientBuilder).setSSLSocketFactory(sslConnectionSocketFactory)

However, if I assert both at once, the test fails (as expected):

  (there was one(httpClientBuilder).setSSLSocketFactory(sslConnectionSocketFactory)) and
  (there was no(httpClientBuilder).setSSLSocketFactory(sslConnectionSocketFactory))

I don't understand why the test passes with either one of these conditions, but not with both. Am I writing something incorrectly?

Aucun commentaire:

Enregistrer un commentaire