我是测试框架的新手,对测试知之甚少,但我想在这里为这个场景编写单元测试用例。
到目前为止,我已经知道应该在它之上构建一个特性并让这个实用程序扩展这个特性但是之后我发现它很难继续。
object utility{
def abc(a: String, b: Int ): String={}
def bcd(): Int = {}
}
我正在使用flatspec和MockFactory
scala 2.11
和sbt
具有以下依赖关系
libraryDependencies += "org.scalamock" %% "scalamock" % "4.1.0" % "test",
libraryDependencies += "org.scalatest" %% "scalatest" % "3.0.4" % "test"
我们将不胜感激 感谢
答案 0 :(得分:3)
trait Utility {
def abc(a: String, b: Int ): String
def bcd(): Int
}
object RealUtil extends Utility {
def abc(a: String, b: Int ): String= ??? //real implementation
def bcd(): Int = ???
}
class UsesUtil(util: Utility) {
def doSth(): Int = util.bcd()
}
// allows prod usage like this UsesUtil().doSth
object UsesUtil {
def apply(util: Utility = RealUtil): UsesUtil = new UsesUtil(util)
}
class HereAreTests {
// use in tests
val mockedUtility = new Utility {
def abc(a: String, b: Int ): String= "mock"
def bcd(): Int = 42
}
// test here
val useUtilClass = new UsesUtil(mockedUtility)
val resultFromMock = useUtilClass.doSth()
assert(resultFromMock == 42)
}
答案 1 :(得分:2)
rincewind的另一个建议是使用Mockito:
"org.mockito" % "mockito-core" % "2.9.0" % "test"
trait Utility {
def abc(a: String, b: Int ): String={}
def bcd(): Int = {}
}
object RealUtil extends Utility {
def abc(a: String, b: Int ): String= ??? //real implementation
def bcd(): Int = ???
}
class UsesUtil(util: Utility) {
// do sth with util
}
class HereAreTests extends MockitoSugar {
// use in tests
val mockedUtility = mock[Utility]
"this" should "do something" in {
when(mockedUtility.abc(
ArgumentMatchers.eq("some input string"),
ArgumentMatchers.anyInt()
)).thenReturn("my string")
// tests which call the `abc` function with input of "some input string" and any number
}
}
当我想要更具体地了解我的输入时,我发现这更有帮助。这意味着您可以模拟特定的预期输入和输出,并且每次您想要测试不同的东西时都必须重新声明val
。
但这只是个人偏好,我想:)