在Scala中的一个测试类中组合模拟和普通测试

时间:2014-08-10 09:54:12

标签: scala mocking tdd

代码

测试

package com.utrecht.numbersequences

import org.scalatest.FunSuite
import org.scalatest.BeforeAndAfter
import org.scalatest.mock.MockitoSugar
import org.mockito.Mockito._

class NumberSequencesTests extends FunSuite with BeforeAndAfter with MockitoSugar {
  test("randomInteger") {
    val m = mock[NumberSequences]
    when(m.randomInteger(5)).thenReturn(5)
    assert(5 === m.randomInteger(5))
  }

  test("squareRoot") {
    assert(NumberSequences.squareRoot(25) === 5)
  }
}

package com.utrecht.numbersequences

import scala.collection.immutable.Stream.consWrapper

class NumberSequences {
  def randomInteger(a: Int) : Int = {
    scala.util.Random.nextInt(a) + 1
  }

  def squareRoot(a: Double) : Double = {
    math.sqrt(a)
  }
}

结果

预期

> test
[info] NumberSequencesTests:
[info] - randomInteger
[info] - squareRoot
[info] Passed: Total 2, Failed 0, Errors 0, Passed 2
[success] Total time: 1 s, completed Aug 10, 2014 11:46:44 AM
>

电流

为了测试 squareRoot ,需要将NumberSequences类更改为对象。完成此操作后,可以测试squareRoot,但模拟失败。一旦反转,模拟测试就会通过,但squareRoot测试再次失败。

> test
[info] Compiling 1 Scala source to C:\path\to\developme
nt\scalaNumberSequences\target\scala-2.10\test-classes...
[error] C:\path\to\scalaNumberSequences\src
\test\scala\com\utrecht\numbersequences\NumberSequencesTest.scala:16: not found:
 value NumberSequences
[error]     assert(NumberSequences.squareRoot(25) === 5)
[error]            ^
[error] one error found
[error] (test:compile) Compilation failed
[error] Total time: 1 s, completed Aug 10, 2014 11:47:13 AM
>

1 个答案:

答案 0 :(得分:2)

您必须实例化NumberSequences个对象,因为它是class,而不是objectcompanion object

assert(new NumberSequences().squareRoot(25) === 5)

使用此语法:

assert(NumberSequences.squareRoot(25) === 5)

你需要这个:

object NumberSequences {
    def squareRoot(a: Double) : Double = {
      math.sqrt(a)
    }
}

但是因为你需要模拟它(在第一次测试中),我宁愿使用第一个解决方案:实例化类。