l33tHax0r
l33tHax0r

Reputation: 1721

Is it possible to mock multiple Scala Objects in the same test?

Say I have the following object I want to test

object ObjectToTest {

  def apply() = {
    val example = List.fill(5)(CaseClassExample("here", "there"))
    ChildObject(example.tail) + " " + ChildObject2(example.tail)
  }

}

where both child objects look like this

object ChildObject2 {

  def apply(param1: Seq[CaseClassExample]) = {
    "not mocked"
  }

}

object ChildObject {

  def apply(param1: Seq[CaseClassExample]) = {
    "not mocked"
  }

}

Is it possible to write a test that mocks the two child objects being used in the object under test?

Upvotes: 0

Views: 561

Answers (1)

l33tHax0r
l33tHax0r

Reputation: 1721

Possible? Yes. Advised? No Idea.

We could write the following tests uisng mockito-scala and scalatest to mock both objects


class ObjectToTestSpec extends AnyWordSpec with MockitoSugar with ArgumentMatchersSugar {

  "ObjectToTest" should {
    
    "return not mocked when not mocked" in {
      ObjectToTest.apply2() mustEqual "not mocked not mocked"
    }

    "return mocked when mocked anySeq" in {
      withObjectMocked[ChildObject.type] {
        withObjectMocked[ChildObject2.type ] {
          when(ChildObject(anySeq[CaseClassExample])) thenReturn "mocked"
          when(ChildObject2(anySeq[CaseClassExample])) thenReturn "mocked"
          ObjectToTest.apply2() mustEqual "mocked mocked"
        }
      }

    }

    "return mocked when mocked eqTo" in {
      withObjectMocked[ChildObject.type] {
        withObjectMocked[ChildObject2.type] {
          when(ChildObject(eqTo(List.fill(4)(CaseClassExample("here","there"))))) thenReturn "mocked"
          when(ChildObject2(eqTo(List.fill(4)(CaseClassExample("here","there"))))) thenReturn "mocked"
          ObjectToTest.apply2() mustEqual "mocked mocked"
        }

      }

    }
  }
}

Upvotes: 2

Related Questions