Introdução ao Hibernate (Testes dos Serviços) - Parte 12

12. setembro 2011 00:57 by BBranquinho in   //  Tags:   //   Comentários (0)

Neste post continuarei a criação do ParserDatabase e dos testes dos serviços.

A classe ParserDatabase é usada apenas para transformar Entidades para Beans e vice-versa. A seguir é mostrada a implementação deste ParserDatabase.

package br.com.branquinho.hibernate.database.utils;

import java.util.ArrayList;
import java.util.List;

import br.com.branquinho.hibernate.database.entities.CategoryEntity;
import br.com.branquinho.hibernate.database.entities.ProductEntity;
import br.com.branquinho.hibernate.utils.database.beans.CategoryBean;
import br.com.branquinho.hibernate.utils.database.beans.ProductBean;

public class ParserDatabase {

	public static CategoryEntity parserBeanToEntity(CategoryBean categoryBean) {

		CategoryEntity categoryEntity = new CategoryEntity();

		// ID
		categoryEntity.setId(categoryBean.getId());

		// Description
		categoryEntity.setDescription(categoryBean.getDescription());

		// Name
		categoryEntity.setName(categoryBean.getName());

		// Products
		List<ProductEntity> products = parseProductBeansToEntities(categoryBean.getProducts());

		categoryEntity.setProducts(products);

		return categoryEntity;

	}

	public static ProductEntity parserBeanToEntity(ProductBean productBean) {

		ProductEntity product = new ProductEntity();

		// ID
		product.setId(productBean.getId());

		// Description
		product.setDescription(productBean.getDescription());

		// Price
		product.setPrice(productBean.getPrice());

		// Category
		CategoryEntity category = parserBeanToEntity(productBean.getCategory());

		product.setCategory(category);

		return product;

	}

	public static List<ProductEntity> parseProductBeansToEntities(List<ProductBean> productsBean) {

		List<ProductEntity> productsEntity = new ArrayList<ProductEntity>();

		if (productsBean != null) {
			for (ProductBean product : productsBean) {
				productsEntity.add(parserBeanToEntity(product));
			}
		}

		return productsEntity;

	}

	public static List<CategoryEntity> parseCategoryBeansToEntities(List<CategoryBean> categoriesBean) {

		List<CategoryEntity> categoriesEntity = new ArrayList<CategoryEntity>();

		if (categoriesBean != null) {
			for (CategoryBean category : categoriesBean) {
				categoriesEntity.add(parserBeanToEntity(category));
			}
		}

		return categoriesEntity;

	}

	public static CategoryBean parserEntityToBean(CategoryEntity categoryEntity) {

		CategoryBean categoryBean = new CategoryBean();

		// ID
		categoryBean.setId(categoryEntity.getId());

		// Description
		categoryBean.setDescription(categoryEntity.getDescription());

		// Name
		categoryBean.setName(categoryEntity.getName());

		// Products
		List<ProductBean> products = parseProductEntitiesToBeans(categoryEntity.getProducts());

		categoryBean.setProducts(products);

		return categoryBean;

	}

	public static ProductBean parserEntityToBean(ProductEntity productEntity) {

		ProductBean productBean = new ProductBean();

		// ID
		productBean.setId(productEntity.getId());

		// Description
		productBean.setDescription(productEntity.getDescription());

		// Price
		productBean.setPrice(productEntity.getPrice());

		// Category
		productBean
				.setCategory(parserEntityToBean(productEntity.getCategory()));

		return productBean;

	}

	public static List<ProductBean> parseProductEntitiesToBeans(List<ProductEntity> productsEntity) {

		List<ProductBean> productsBean = new ArrayList<ProductBean>();

		if (productsEntity != null) {
			for (ProductEntity product : productsEntity) {
				productsBean.add(parserEntityToBean(product));
			}
		}

		return productsBean;

	}

	public static List<CategoryBean> parseCategoryEntitiesToBeans(List<CategoryEntity> categoriesEntity) {

		List<CategoryBean> categoriesBean = new ArrayList<CategoryBean>();

		if (categoriesEntity != null) {
			for (CategoryEntity category : categoriesEntity) {
				categoriesBean.add(parserEntityToBean(category));
			}
		}

		return categoriesBean;

	}

}

Os testes dos serviços são realizados utilizando JUnits. Em nosso exemplo são apenas dois testes, um de busca e outro de inserção. Fiquem a vontade para fazer um teste unitário para cada serviço. A seguir é mostrado o código responsável por estes testes.

package br.com.branquinho.hibernate.database.test;

import java.util.List;

import org.apache.log4j.Logger;
import org.junit.BeforeClass;
import org.junit.Test;

import br.com.branquinho.hibernate.database.ServicesFactory;
import br.com.branquinho.hibernate.database.interfaces.IDaoFactory;
import br.com.branquinho.hibernate.database.utils.DaoFactory;
import br.com.branquinho.hibernate.utils.database.beans.CategoryBean;
import br.com.branquinho.hibernate.utils.database.beans.ProductBean;
import br.com.branquinho.hibernate.utils.database.interfaces.IServicesFactory;

public class ServicesDatabaseTest {

	private static final Logger logger = Logger.getLogger(ServicesDatabaseTest.class);

	private static final IDaoFactory daoFactory = new DaoFactory();

	private static final IServicesFactory serviceFactory = new ServicesFactory(daoFactory);

	@BeforeClass
	public static void beforeClass() {
		logger.info("Instantiate DAO Factory and Service Factory.");
	}

	@Test
	public void testFindAll() {

		logger.info("Find all registers.");

		// Find all categories.
		List<CategoryBean> categories = serviceFactory.getCategoryService().findAllCategories();

		for (CategoryBean category : categories) {
			logger.info(String.format("Category [%s]", category));
		}

		// Find all products.
		List<ProductBean> products = serviceFactory.getProductServices().findAllProducts();

		for (ProductBean product : products) {
			logger.info(String.format("Product [%s]", product));
		}
	}

	@Test
	public void testInsert() {
		logger.info("Testing insertion.");

		// Test insert a category.
		String tmpCategory = "Category 05";

		CategoryBean category = new CategoryBean();

		category.setDescription(String.format("Description of the %s.", tmpCategory));
		category.setName(String.format("Name %s.", tmpCategory));

		Long idCategory = serviceFactory.getCategoryService().insert(category);

		// Test insert a product.
		String tmpProduct = "Product 05";

		ProductBean product = new ProductBean();

		product.setDescription(String.format("Description of the %s.", tmpProduct));
		product.setName(String.format("Name %s.", tmpProduct));
		product.setPrice(12.02d);
		product.setCategory(new CategoryBean(idCategory));

		serviceFactory.getProductServices().insert(product);
	}

}

O próximo vídeo mostra a implementação destas classes.

 

Com isso finalizamos o módulo responsável por gerenciar o banco de dados e disponibilizar serviços.

No próximo post continuo o trabalho mostrando a integração do hibernate-application e hibernate-database.

Até o próximo post pessoal.

Comentar

  Country flag

biuquote
  • Comentário
  • Pré-visualização
Loading

WPattern

O objetivo deste blog é de disponibilizar os resultados dos meus estudos. Não será tratada apenas uma tecnologia ou área, mas qualquer tópico que seja interessante e possa contribuir com a comunidade de desenvolvedores, comunidade científica e meus alunos. Entretanto, meus trabalhos sempre estão voltado principalmente para as tecnologias .NET, Java e C/C++.

Posts Recentes

Google Translator

JetBrains

JetBrains: Ferramentas de desenvolvimento com .NET.

ReSharper: Excelente ferramenta para .NET.