testng - 登录后面的 HTTP REST 测试



我已经设置了一个使用 testNG/Maven/Springs RestTemplate 测试 HTTP REST 应用程序的项目。

我用它来做功能测试,对 REST 应用程序的多次调用包含在套件中以模仿用户进程。

这工作正常。

知道我们已启用身份验证。

问题是如何使用testNG做到这一点?如何(仅一次)登录我的测试套件。

我可以使用@BeforeSuite并调用登录页面,登录并捕获所有其他请求所需的cookie。但是我在哪里存储这个cookie,以便所有测试用例都可以添加它?当然,我必须向测试中添加一些代码才能添加cookie....但是我该如何掌握它呢?

我调查了@parameter和@dataprovider,但这些似乎对我没有多大帮助......

任何帮助/建议都非常感谢。

我已经创建了一个可行的解决方案。

我所做的是使用单例对象和@dataprovider,以测试数据:数据提供程序创建单一实例对象。单例对象在其创建过程中调用登录页面,并将在每次来自不同测试的调用后返回 cookie 信息。

也许这有点黑客,但它有效。

单例解决方案有点苛刻,因为它可以防止将来对测试进行任何并行化。

有一些方法可以解决这个问题。一种是将 ITestContext 实例传递给您的 @BeforeSuite/@BeforeTest 并@BeforeClass配置方法,并通过每个实例中的测试上下文放置/获取参数:

public class Test {
    /** Property Foo is set once per Suite */
    protected String foo;
    /** Property Foo is set once per Test */
    protected String bar;
    /**
     * As this method is executed only once for all inheriting instances before the test     suite starts this method puts
     * any configuration/resources needed by test implementations into the test context.
     *
     * @param context test context for storing test conf data
     */
    @BeforeSuite
    public void beforeSuite(ITestContext context) {
        context.setAttribute("foo", "I was set in @BeforeSuite");
    }
    /**   
     * As this method is executed only once for all inheriting instances before the test starts this method puts any
     * configuration/resources needed by test implementations into the test context.
     *
     * @param context test context for storing test conf data
     */
    @BeforeTest(alwaysRun = true)
    public void beforeTest(ITestContext context) {
        context.setAttribute("bar", "I was set in @BeforeTest");
    }
    /**
     * This method is run before the first method of a test instance is started and gets all required configuration from
     * the test context.
     *
     * @param context test context to retrieve conf data from.
     */
    @BeforeClass
    public void beforeClass(ITestContext context) {
        foo = (String) context.getAttribute("foo");
        bar = (String) context.getAttribute("bar");
    }
}

即使 @BeforeSuite/Test/Class 方法位于实际测试实现的超类中,此解决方案也有效。

如果您要在Spring Security上委派登录,并且后端不存储状态(意味着仅授权隔离的请求),则无需对其进行测试。这意味着您可以在测试中禁用身份验证(获取 cookie)。这样,您就可以将测试本身与授权分离。

但是,如果您不想这样做。如果您在套件中组织测试,则可以设置私人成员。Cookie 将是响应中的header auth

@TestSuite
public void mySuite {
    private String cookie;
    @BeforeSuite public void login() {
         // Obtain cookie
         this.cookie = cookie;
    }
 ////// Rest of suite

另一种查看方法是执行登录作为测试的一部分。

我不知道还有什么比这更优雅的方法了。

最新更新