тестеры записываемся на копайлот
Первый шаг:
Идете и даете своему бекендеру пизды, чтобы он замутил свагер
Второй шаг:
Копируете курл из сваггера и типовые ответы на запрос
Третий шаг:
Идете в чатгпт или копайлот и делаете вот примерно такой запрос
Hi. I have a curl reqest. Its a login request to my service and i want to make autotests for this request. Write tests for me. Use Java language and okhttp3 library. Each test should be a separate method.
This is curl:curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' -d '{ \ "email": "m%40m.ru", \ "password": "password" \ }' 'ИМАДЖИНИРУЙ ТУТ ЮРЛ'Threre is a 200 response, that comes if user go with correct credetensials. Token changes each time as user logins:{ "refresh_token": ИМАДЖИНИРУЙ ЧТО ТУТ ТОКЕН", "token": "ИМАДЖИНИРУЙ ЧТО ТУТ ТОКЕН" }Threre is a 401 response if user go with invalid credetentials:{ "status": 401, "data": { "email": "donotoreply@.org" }, "error": 2, "message": "Wrong email or password" }
Четвертый шаг:
Ждете пока чудо Омниссии думает и выдает нам примерно вот что
import okhttp3.*;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class LoginServiceTest {
private static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
private static final OkHttpClient client = new OkHttpClient();
private String post(String url, String json) throws IOException {
RequestBody body = RequestBody.create(json, JSON);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
try (Response response = client.newCall(request).execute()) {
return response.body().string();
}
}
@Test
public void testSuccessfulLogin() throws IOException {
String json = "{ \"email\": \"m@m.ru\", \"password\": \"password\" }";
String response = post("ИМАДЖИНИРУЙ ТУТ ЮРЛ", json);
// Assert that the response contains a token
assert(response.contains("token"));
}
@Test
public void testUnsuccessfulLogin() throws IOException {
String json = "{ \"email\": \"wrong@m.ru\", \"password\": \"wrongpassword\" }";
String response = post("ИМАДЖИНИРУЙ ТУТ ЮРЛ", json);
// Assert that the response contains an error message
assertEquals("{\"status\":401,\"data\":{\"email\":\"donotoreply@.org\"},\"error\":2,\"message\":\"Wrong email or password\"}", response);
}
}
Пятый шаг:
Подумать самому все же придется, смотрим что тут не так. Хуемое, джейсончики как стринги прямо в коде, это беспонтово. Еще можно урл объявлять прям в самом начале, тестим то токо один метод.
Can you fix what you write please. Request urlИМАДЖИНИРУЙ ТУТ ЮРЛshould not be specified in tests it should be specified as a variable in the begining of class.
Also please make request body as separate class with getters and setters
Шестой шаг:
Оно нам нахуевертит вот такого примерно
import okhttp3.*;
import org.junit.jupiter.api.Test;
import com.google.gson.Gson;
import java.io.IOException;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class LoginServiceTest {
private static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
private static final OkHttpClient client = new OkHttpClient();
private static final String URL = "ИМАДЖИНИРУЙ ТУТ ЮРЛ";
private static final Gson gson = new Gson();
private String post(String url, LoginBody body) throws IOException {
RequestBody requestBody = RequestBody.create(gson.toJson(body), JSON);
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
try (Response response = client.newCall(request).execute()) {
return response.body().string();
}
}
@Test
public void testSuccessfulLogin() throws IOException {
LoginBody body = new LoginBody("m@m.ru", "password");
String response = post(URL, body);
// Assert that the response contains a token
assert(response.contains("token"));
}
@Test
public void testUnsuccessfulLogin() throws IOException {
LoginBody body = new LoginBody("wrong@m.ru", "wrongpassword");
String response = post(URL, body);
// Assert that the response contains an error message
assertEquals("{\"status\":401,\"data\":{\"email\":\"donotoreply@.org\"},\"error\":2,\"message\":\"Wrong email or password\"}", response);
}
static class LoginBody {
private String email;
private String password;
public LoginBody(String email, String password) {
this.email = email;
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
}Седьмой шаг:
Думаем по новой, вспоминаем, что есть плагин который сам ставит геттеры сеттеры. Пишем.
Please use Lombok annotations and change LoginBody class
Восьмой шаг:
import okhttp3.*;
import org.junit.jupiter.api.Test;
import com.google.gson.Gson;
import java.io.IOException;
import static org.junit.jupiter.api.Assertions.assertEquals;
import lombok.Getter;
import lombok.Setter;
import lombok.AllArgsConstructor;
public class LoginServiceTest {
private static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
private static final OkHttpClient client = new OkHttpClient();
private static final String URL = "ИМАДЖИНИРУЙ ТУТ ЮРЛ";
private static final Gson gson = new Gson();
private String post(String url, LoginBody body) throws IOException {
RequestBody requestBody = RequestBody.create(gson.toJson(body), JSON);
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
try (Response response = client.newCall(request).execute()) {
return response.body().string();
}
}
@Test
public void testSuccessfulLogin() throws IOException {
LoginBody body = new LoginBody("m@m.ru", "password");
String response = post(URL, body);
// Assert that the response contains a token
assert(response.contains("token"));
}
@Test
public void testUnsuccessfulLogin() throws IOException {
LoginBody body = new LoginBody("wrong@m.ru", "wrongpassword");
String response = post(URL, body);
// Assert that the response contains an error message
assertEquals("{\"status\":401,\"data\":{\"email\":\"donotoreply@.org\"},\"error\":2,\"message\":\"Wrong email or password\"}", response);
}
@Getter
@Setter
@AllArgsConstructor
static class LoginBody {
private String email;
private String password;
}
}Девятый шаг:
Бля, забыли про респонс боди, вежливо просим поправить.
Thank you. Now please make a response body as sepatate class
Десятый шаг:
import okhttp3.*;
import org.junit.jupiter.api.Test;
import com.google.gson.Gson;
import java.io.IOException;
import static org.junit.jupiter.api.Assertions.assertEquals;
import lombok.Getter;
import lombok.Setter;
import lombok.AllArgsConstructor;
public class LoginServiceTest {
private static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
private static final OkHttpClient client = new OkHttpClient();
private static final String URL = "ИМАДЖИНИРУЙ ТУТ ЮРЛ";
private static final Gson gson = new Gson();
private ResponseBody post(String url, LoginBody body) throws IOException {
RequestBody requestBody = RequestBody.create(gson.toJson(body), JSON);
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
try (Response response = client.newCall(request).execute()) {
return gson.fromJson(response.body().string(), ResponseBody.class);
}
}
@Test
public void testSuccessfulLogin() throws IOException {
LoginBody body = new LoginBody("m@m.ru", "password");
ResponseBody response = post(URL, body);
// Assert that the response contains a token
assert(response.getToken() != null);
}
@Test
public void testUnsuccessfulLogin() throws IOException {
LoginBody body = new LoginBody("wrong@m.ru", "wrongpassword");
ResponseBody response = post(URL, body);
// Assert that the response contains an error message
assertEquals("Wrong email or password", response.getMessage());
}
@Getter
@Setter
@AllArgsConstructor
static class LoginBody {
private String email;
private String password;
}
@Getter
@Setter
static class ResponseBody {
private String token;
private String refresh_token;
private int status;
private Data data;
private int error;
private String message;
@Getter
@Setter
static class Data {
private String email;
}
}
}Одиннадцатый шаг:
Так, ну ладно, пора поработать руками. Сразу видим какую-то залупу с респос боди, некрасиво, но нам похуй, работает же.
Копируем весь код в IDEA, сразу видим что все красное и ничо не работает, нажимаем пару раз Cntrl+Enter, ага, неправильно библиотеки подтянули. Кликаем cntrl+enter пока большинство проблем не решится. Остальное правим руками.
Итого что вышло по коду:
package http;
import okhttp3.*;
import org.junit.Test;
import com.google.gson.Gson;
import java.io.IOException;
import static org.junit.Assert.assertEquals;
import lombok.Getter;
import lombok.Setter;
import lombok.AllArgsConstructor;
public class LoginServiceTest {
private static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
private static final OkHttpClient client = new OkHttpClient();
private static final String URL = "ИМАДЖИНИРУЙ ТУТ ЮРЛ";
private static final Gson gson = new Gson();
private ResponseBody post(String url, LoginBody body) throws IOException {
RequestBody requestBody = RequestBody.create(gson.toJson(body), JSON);
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
try (Response response = client.newCall(request).execute()) {
return gson.fromJson(response.body().string(), ResponseBody.class);
}
}
@Test
public void testSuccessfulLogin() throws IOException {
LoginBody body = new LoginBody("m@m.ru", "password");
ResponseBody response = post(URL, body);
// Assert that the response contains a token
assert(response.getToken() != null);
}
@Test
public void testUnsuccessfulLogin() throws IOException {
LoginBody body = new LoginBody("wrong@m.ru", "wrongpassword");
ResponseBody response = post(URL, body);
// Assert that the response contains an error message
assertEquals("Wrong email or password", response.getMessage());
}
@Getter
@Setter
@AllArgsConstructor
static class LoginBody {
private String email;
private String password;
}
@Getter
@Setter
static class ResponseBody {
private String token;
private String refresh_token;
private int status;
private Data data;
private int error;
private String message;
@Getter
@Setter
static class Data {
private String email;
}
}
}