【发布时间】:2018-03-19 21:55:46
【问题描述】:
在 Spock 测试中,我希望能够更改方法内变量的值。
例如,我想将 uName 的值更改为“John”。或者对于另一个测试,在进行测试时将 uCat 的值更改为“seller”。如何在测试中确保执行 else 语句中的两种方法:postComment 和 sendEmails。
class userService {
void userComment()
{
def uName = "test123"
def uCat = Category.getUserCategory(uName)
if (uCat.empty){
println("no categories to process")
}
else
{
postComment(uName)
batchJob.sendEmail(uName)
}
}
}
class userServiceSpec extends Specification{
def "test userComment"()
{
given:
?????
when:
?????
then:
1 * postComment(_)
then:
1* batchJob.sendEmail(_)
}
}
【问题讨论】:
-
对你来说坏消息:你不能在测试中改变局部变量——你不应该!类或方法应该是测试的黑匣子。重新设计您的应用程序以进行解耦和dependency injection,然后您可以只注入用户名或批处理作业等依赖项。问题不在于测试,而在于应用程序不可测试,因为它在内部创建了自己的依赖项,而不是注入它们。
标签: java unit-testing mocking spock stub