如何在phpunit中干净地构建测试
我是PHP的新手,来自Ruby背景。在Ruby中,我们可以使用上下文
构建测试非常干净。
例如 -
describe "CheckoutService"
context "with a user who has a card" do
let(user) { mock_user }
let(card) { mock_valid_card }
before do
user.card = card
user.save()
// more related complicated setup could go here
end
context "with valid card" do
it "checks out smoothly" do
user.checkout()
assert_success()
end
end
context "with invalid card" do
let(card) { mock_invalid_card}
it "throws error" do
user.checkout()
assert_failure()
end
end
end
context "with a user who doesn't have a card" do
it "redirects to add card" do
user.checkout()
assert_redirect()
end
end
end
在这里,每个上下文
可以在>和 block之后具有自己的,我可以在其中干净地设置特定的测试而无需重复。
Phpunit中有这样的事情吗?
PS-我觉得这与Phpunit提供的DataProviders不同。他们似乎重复了相同的测试,但是对于不同的参数,而使用上下文
我们在测试设置周围具有更多的自由度。此外,测试更可读性
I'm new to PhP and coming from a Ruby background. In Ruby we could structure tests using context
blocks very cleanly.
For example -
describe "CheckoutService"
context "with a user who has a card" do
let(user) { mock_user }
let(card) { mock_valid_card }
before do
user.card = card
user.save()
// more related complicated setup could go here
end
context "with valid card" do
it "checks out smoothly" do
user.checkout()
assert_success()
end
end
context "with invalid card" do
let(card) { mock_invalid_card}
it "throws error" do
user.checkout()
assert_failure()
end
end
end
context "with a user who doesn't have a card" do
it "redirects to add card" do
user.checkout()
assert_redirect()
end
end
end
Here, each context
can have its own before
and after
block where I can setup the specific tests cleanly and without much repetition.
Is there such a thing in PhpUnit?
PS - I feel this is different from DataProviders that PhPUnit provides. They seem to repeat the same test but for different parameters, whereas using context
we have more freedom around the setup of the test. Additionally the test is much more readable
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论