如何在phpunit中干净地构建测试

发布于 2025-02-09 20:26:34 字数 1180 浏览 1 评论 0原文

我是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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文