我是测试框架的新手,对测试几乎没有任何想法,但我想在这里为场景编写一个单元测试用例。
到目前为止,我必须知道应该在其顶部建立一个特征,并让该实用程序扩展该特征,但是在那之后,我发现很难进行。
object utility{
def abc(a: String, b: Int ): String={}
def bcd(): Int = {}
}
我正在使用flatspec和oilefactory
scala 2.11
和 sbt
带有以下依赖关系
libraryDependencies += "org.scalamock" %% "scalamock" % "4.1.0" % "test",
libraryDependencies += "org.scalatest" %% "scalatest" % "3.0.4" % "test"
您的帮助将不胜感激谢谢
通常您会做STH。这样:
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)
}
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
。
那只是个人喜好,我猜:(