【发布时间】:2014-06-24 11:32:17
【问题描述】:
我是 Spock 的新手,我想对这个类进行单元测试。在类中有一个验证产品的方法。要通过验证,产品必须具有 fullPrice 并且必须包含所有其他价格,否则应抛出异常。
class PriceValidator {
private final Logger logger = Logger.getLogger(MyService.class)
void validate (Product product) throws SubsystemException {
if (!product.fullPrice || !product.fullPrice.priceInclVAT || !product.fullPrice.priceExclVAT || !product.fullPrice.vat) {
String message = "No price found!"
logger.error(message)
throw new SubsystemException(
Subsystem.MySystem,
FailureCause.NO_PRICE_FOUND,
message
)
}
}
}
我已经尝试以多种方式对此进行测试,但没有任何运气。我猜我需要模拟,但这对我来说也是新的。这是我尝试过的一个测试示例,导致“测试框架意外退出”(并且所有价格都是字符串):
class PriceValidatorTest extends Specification {
@Unroll
def "No price should throw an exception"() {
given:
PriceValidator priceValidator = new PriceValidator()
Product product = Mock()
when:
product.fullPrice != null
product.fullPrice.priceInclVAT = "100"
product.fullPrice.priceExclVAT = "70"
product.fullPrice.vat = null
priceValidator.validate(product)
then:
thrown(SubsystemException)
}
}
有人对如何测试 PriceValidator 有建议吗?
【问题讨论】:
-
如果您觉得我的回答有用,请接受并点赞。
标签: validation unit-testing groovy intellij-idea spock