如何使用RestURE测试需要身份验证的Rest API [英] How to test Rest API which require authentication using Rest assured

查看:169
本文介绍了如何使用RestURE测试需要身份验证的Rest API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在获得Json响应之前测试需要身份验证的Rest API. 考试.如果我想访问其余的API: http://192.168.xx .xx:9000/dashboards/all/list/m1/p1/sch1

I want to test a Rest API which require authentication, before getting the Json response. FOr exa. If i want to visit rest API: http://192.168.xx.xx:9000/dashboards/all/list/m1/p1/sch1

然后

如果我尚未登录,那么这会将我重定向到Login HTML页面,并且在登录后,这将向我显示Json输出.

if I am not already logged in , then this will redirect me to Login HTML page, and after login, this will show me the Json output.

现在,我想用同样的方式在Java中编写一个放心的代码: 我不知道,是否可以使用此登录.

Now I want to write a Rest assured code in java for same: I dont know , whether this is possible to do login using this or not.

我为此写了一个简单的代码:

SO I written a simple code for same::

public class TestNGSimpleTest1 {

    @Test
    public void testAdd() {
            //expect().
            //statusCode(400).
            //body("Status", equalTo("Success")).
            //when().
            //get("http://localhost:9000/dashboards/all/list/m1/p1/sch1");
            //System.out.println("Response received is ::" +res);   
            Response res = get("http://localhost:9000/dashboards/all/list/m1/p1/sch1");
            assertEquals(200,res.getStatusCode());
            String json = res.asString();
            System.out.println("Response received is :: " +json);
    }

因此,这里不是得到Json响应,而是得到HTML源页面响应.

So here instead of getting the Json response, I am getting the HTML source page response.

所以,我的问题是,如果可能的话,如何登录并获得Json响应.

So, my question is if possible, how to do login and get the Json response.

谢谢.

推荐答案

如果您使用的是JIRA的默认身份验证,则需要先行身份验证.下面是示例代码.

If you are using default authentication from JIRA, then preemptive authentication is what you need. Below are the sample code.

RestAssured.baseURI = System.getProperty("baseurl");
PreemptiveBasicAuthScheme authScheme = new PreemptiveBasicAuthScheme();
authScheme.setUserName("admin");
authScheme.setPassword("admin");
RestAssured.authentication = authScheme;

示例代码将帮助您在发送每个请求之前进行身份验证.

The sample code will help you do the authentication before every request you send.

这篇关于如何使用RestURE测试需要身份验证的Rest API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆