Всем привет. В предыдущей статье мы расморели создание проекта и построение основы API. Пришло время рассмотреть реализацию операций и добавить тестовые данные. В реальном приложении зачастую используется какая-то база данных , например, SQL. Но так как мы тестируем только заглушку, то для хранения данных нам достаточно будет использовать какую-то коллекцию, например, HashMap. Ниже представлен класс со статическими методами выполнения операций и добавления данных.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
package com.automationrhapsody.reststub.persistence; import com.automationrhapsody.reststub.data.Person; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class PersonDB { private static Map<Integer, Person> persons = new HashMap<Integer, Person>(); static { persons.put(1, new Person(1, "FN1", "LN1", "email1@email.com")); persons.put(2, new Person(2, "FN2", "LN2", "email2@email.com")); persons.put(3, new Person(3, "FN3", "LN3", "email3@email.com")); persons.put(4, new Person(4, "FN4", "LN4", "email4@email.com")); } public static Person getById(int id) { return persons.get(id); } public static List<Person> getAll() { List<Person> result = new ArrayList<Person>(); for (Integer key : persons.keySet()) { result.add(persons.get(key)); } return result; } public static int getCount() { return persons.size(); } public static void remove() { if (!persons.keySet().isEmpty()) { persons.remove(persons.keySet().toArray()[0]); } } public static String save(Person person) { String result = ""; if (persons.get(person.getId()) != null) { result = "Updated Person with id=" + person.getId(); } else { result = "Added Person with id=" + person.getId(); } persons.put(person.getId(), person); return result; } } |
Создание smoke теста
Для быстрой проверки работы API создадим простой тест, который будет возвращать количество людей. Если значение не будт возвращено или оно будет некорректно, то что-то работает некорректно. Для иллюстрации использования версии с файла конфигурации передадим ее в конструктор.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
package com.automationrhapsody.reststub; import com.automationrhapsody.reststub.persistence.PersonDB; import com.codahale.metrics.health.HealthCheck; public class RestStubCheck extends HealthCheck { private final String version; public RestStubCheck(String version) { this.version = version; } @Override protected Result check() throws Exception { if (PersonDB.getCount() == 0) { return Result.unhealthy("No persons in DB! Version: " + this.version); } return Result.healthy("OK with version: " + this.version + ". Persons count: " + PersonDB.getCount()); } } |
Создание точки запуска приложения
Это завершающий этам создания архитектуры приложения. На данный момент мы имеем данные, сервис, smoke тест. This is execution entry point. В методе main() создается наше приложение и осуществляется его запуск. В методе run() осуществляется создание объекта и проверка метода на работоспособность.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
package com.automationrhapsody.reststub; import com.automationrhapsody.reststub.resources.BookService; import com.automationrhapsody.reststub.resources.PersonService; import io.dropwizard.Application; import io.dropwizard.setup.Environment; public class RestStubApp extends Application<RestStubConfig> { public static void main(String[] args) throws Exception { new RestStubApp().run(args); } @Override public void run(RestStubConfig config, Environment env) { final PersonService personService = new PersonService(); env.jersey().register(personService); final RestStubCheck healthCheck = new RestStubCheck(config.getVersion()); env.healthChecks().register("template", healthCheck); env.jersey().register(healthCheck); } } |
Сборка JAR-файла
Теперь соберем проект в один JAR-файл и запустим его. Для этого откройте файл pom.xml и добавьте <build><plugins> … </plugins></build> в конце.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-shade-plugin</artifactId> <version>1.6</version> <configuration> <createDependencyReducedPom>true</createDependencyReducedPom> <filters> <filter> <artifact>*:*</artifact> <excludes> <exclude>META-INF/*.SF</exclude> <exclude>META-INF/*.DSA</exclude> <exclude>META-INF/*.RSA</exclude> </excludes> </filter> </filters> </configuration> <executions> <execution> <phase>package</phase> <goals> <goal>shade</goal> </goals> <configuration> <transformers> <transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/> <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer"> <mainClass>com.automationrhapsody.reststub.RestStubApp</mainClass> </transformer> </transformers> </configuration> </execution> </executions> </plugin> |
В следующей статье мы запустим наш сервис-заглушку и выполним непосредственное тестирование.