Mostrando las entradas con la etiqueta Mockito. Mostrar todas las entradas
Mostrando las entradas con la etiqueta Mockito. Mostrar todas las entradas

miércoles, 4 de noviembre de 2020

Libros Gratuitos de Java Code Geeks

 

Download IT Guides!

 

Java 8 Features

With no doubts, Java 8 release is the greatest thing in the Java world since Java 5 (released quite a while ago, back in 2004). It brings tons of new features to the Java as a language,...

 
 

Amazon DynamoDB Tutorial

Amazon DynamoDB is a fully managed proprietary NoSQL database service that is offered by Amazon.com as part of the Amazon Web Services portfolio...

 
 

Mockito Programming Cookbook

Mockito is an open source testing framework for Java released under the MIT License. The framework allows the creation of test double objects (mock objects) in automated unit tests for...

 
 

Vaadin Programming Cookbook

Vaadin is an open source web framework for rich Internet applications. In contrast to JavaScript libraries and browser-plugin based solutions, it features a server-side architecture,...

 

miércoles, 21 de febrero de 2018

Libros Gratuitos!!!

Quiero compartir un mail que me llego de java code geeks con unos libros gratuitos:

Download Dev Guides!

 
Moving your application to the cloud isn’t as simple as porting over your code and configurations to someone else’s infrastructure – nor should it be. Cloud computing represents a paradigm shift in the world of application architecture from vertical scalability to horizontal scalability. This new paradigm has much to offer organizations that want to build highly scalable and dynamic applications, but it has its dangers, too – if you’re not careful and purposeful in how you prepare for the cloud, your application could suffer. In this white paper, we’ll discuss how to reap the performance benefits of the cloud and avoid the common pitfalls.
 
 
Cloud computing has been gaining momentum for years. As the technology leaves the early adopter phase and becomes mainstream, many organizations find themselves scrambling to overcome the challenges that come with a more distributed infrastructure. One of those difficulties is getting through a major cloud migration. It is one thing to roll out a few applications and cloud pilot projects, it is an entirely different challenge to start using the cloud across multiple lines of business at massive scale. That is the point that organizations are beginning to reach, and the time has come to take a serious look at cloud migration best practices. Read this eBook to meet the cloud world and its importance for businesses moving to the cloud.
 
 
Mockito is an open source testing framework for Java released under the MIT License. The framework allows the creation of test double objects (mock objects) in automated unit tests for the purpose of Test-driven Development (TDD) or Behavior Driven Development (BDD). In software development there is an opportunity of ensuring that objects perform the behaviors that are expected of them. One approach is to create a test automation framework that actually exercises each of those behaviors and verifies that it performs as expected, even after it is changed. Developers have created mock testing frameworks. These effectively fake some external dependencies so that the object being tested has a consistent interaction with its outside dependencies. 
 
 
JUnit is a unit testing framework to write repeatable tests. JUnit has been important in the development of test-driven development, and is one of a family of unit testing frameworks which is collectively known as xUnit that originated with SUnit. A research survey performed in 2013 across 10,000 Java projects hosted on GitHub found that JUnit, (in a tie with slf4j-api), was the most commonly included external library. (Source) In this ebook, we provide a compilation of JUnit tutorials that will help you kick-start your own programming projects. We cover a wide range of topics, from basic usage and configuration, to multithreaded tests and integration with other testing frameworks. With our straightforward tutorials, you will be able to get your own projects up and running in minimum time.
 

viernes, 9 de septiembre de 2011

Mockito


El objetivo de una prueba unitaria es probar un solo objeto, pero en ciertas ocasiones las colaboraciones entre objetos tienen un acoplamiento alto por lo tanto no puedo probar un objeto sin llamar a otro. Es aquí donde los test se ensucian un poco, en especial si el objeto que deseamos testear depende de algún objeto “pesado” o que tenga interacción con algún otro sistema externo, servidor o base de datos. Por ejemplo testear un objeto que valide el nombre de usuario y la clave en un ldap.

Una estrategia de solución para este problema es usar objetos mocks, los objetos mocks son objetos “de mentira” que permiten simular otro objeto o entidad del sistema. Si vamos a la wikipedia podremos encontrar la siguiente definición:

En la programación orientada a objetos se llaman objetos simulados (pseudoobjetos, mock object, objetos de pega) a los objetos que imitan el comportamiento de objetos reales de una forma controlada. Se usan para probar a otros objetos en pruebas de unidad que esperan mensajes de una clase en particular para sus métodos, al igual que los diseñadores de autos usan un crash dummy cuando simulan un accidente.

En los test de unidad, los objetos simulados se usan para simular el comportamiento de objetos complejos cuando es imposible o impracticable usar al objeto real en la prueba. De paso resuelve el problema del caso de objetos interdependientes, que para probar el primero debe ser usado un objeto no probado aún, lo que invalida la prueba: los objetos simulados son muy simples de construir y devuelven un resultado determinado y de implementación directa, independientemente de los complejos procesos o interacciones que el objeto real pueda tener.
Existen diferentes frameworks en java para hacer mocks, easymock, mockito, etc. Vamos a utilizar mockito.

Mockito es un framework simple, fácil de usar para hacer objetos mocks en java. Tiene una interfaz simple  y natural.

Características:


  • Se pueden crear mocks de interfaces y clases concretas.
  • Verificación de invocaciones (cantidad exacta, al menos una vez, órden de invocación, etc.)
  • El stack trace se mantiene limpio, ya que los errores ocurren en los assert que se hagan (y no dentro del método bajo prueba).
  • Un API más clara para crear stubs y verificaciones.


Vamos a hacer un objeto mock con mockito:

//creamos el mock y el stub


ArrayList instance = mock(ArrayList.class);
doReturn("hola mundo").when(instance).get(0);
 
//ejecutamos la lógica a probar
instance.get(0);     
 
//verificamos que se hayan invocado los métodos
verify(instance).get(0)

Como se puede ver la api es clara y simula el lenguaje natural. En la primera linea creamos un objeto mock de la lista; luego indicamos que cuando se llame el método get con el parámetro 0 debe devolver “hola mundo”. Luego ejecutamos el método y luego se verifica si este método se corrió.

Para agregar este framework a nuestro proyecto maven es solo necesario agregar esta entrada en el pom:



    org.mockito
    mockito-all
    1.8.5