【发布时间】:2014-03-09 15:49:09
【问题描述】:
我正在使用 play 和 mockito 在我的 scala 上运行测试。
这是我的代码:
@RunWith(classOf[JUnitRunner])
class ProductServiceTests extends Specification
with ProductRepositoryComponent
with ProductServiceComponentImpl
with Mockito
{
val productRepository = mock[ProductRepository]
val productId = "d3d08285-512f-46a6-811f-1abeb94ebb98"
val product:Product = new Product(Option(productId), "default name", "default description", new References(Some("1"), Some("1"), Some("1"), Some("1")))
val language = "en_US"
val tenantId = ""
def mockStuff = {
productRepository.addProduct(any[String], any[String], any[Product]) returns
product.id.get
productRepository.updateProduct(any[String], any[String], any[Product]) returns
product.id.get
}
step(mockStuff)
"ProductService" should {
"add minimal product to product repository" in {
val result = productService.addProduct(language, tenantId, product)
result mustNotEqual null
result must beAnInstanceOf[DTOResponse[String]]
val resultAsStr = result.asInstanceOf[DTOResponse[String]].get
resultAsStr.length mustEqual 36 //Guid length
resultAsStr mustEqual productId
}
//How can i override addProduct - So that from now on, it will use the exception throwing add Product.. (commented one)
"update product in repository" in {
val result = productService.addProduct("he_IL", tenantId, product)
result mustNotEqual null
result must beAnInstanceOf[DTOResponse[String]]
val resultAsStr = result.asInstanceOf[DTOResponse[String]].get
resultAsStr.length mustEqual 36 //Guid length
resultAsStr mustEqual productId
}
}
}
我应该在里面有 2 个 in。我如何覆盖第二个 in 的 addProduct 方法?
我的问题是我想模拟 2 个 addProduct 函数,一个可以,另一个无效,因为 Id 已经存在..
谢谢!
【问题讨论】:
-
我建议从 mockStuff 中提取
productRepository.addProduct ...并将其放入每个相应的“in”中,并为每个测试使用适当的参数 -
提取方法并放入in是什么意思?你可以给样本作为答案吗?谢谢
-
您的示例引用了大量未定义的类型,因此重写非常痛苦......
标签: scala junit mockito playframework-2.1