No tienes acceso a esta clase

¡Continúa aprendiendo! Únete y comienza a potenciar tu carrera

Convierte tus certificados en títulos universitarios en USA

Antes: $249

Currency
$209

Paga en 4 cuotas sin intereses

Paga en 4 cuotas sin intereses
Suscríbete

Termina en:

18 Días
13 Hrs
31 Min
19 Seg
Curso Básico de Testing en Java

Curso Básico de Testing en Java

Ferran Maylinch Carrasco

Ferran Maylinch Carrasco

App de Películas: Test de Negocio

17/24
Recursos

Aportes 22

Preguntas 3

Ordenar por:

¿Quieres ver más aportes, preguntas y respuestas de la comunidad?

Por si alguien quiere evitar la fatiga de escribir las películas

Arrays.asList(
	new Movie(1, "Dark Knight", 152, Genre.ACTION),
	new Movie(2, "Memento", 113, Genre.THRILLER),
	new Movie(3, "There's Something About Marty", 119, Genre.COMEDY),
	new Movie(4, "Super 8", 112, Genre.THRILLER),
	new Movie(5, "Scream", 111, Genre.HORROR),
	new Movie(6, "Home Alone", 103, Genre.COMEDY),
	new Movie(7, "Matrix", 136, Genre.ACTION)
)

Como opción a todos, para hacer los asserts a mi me gusta AssertJ, puedes concatenar muchas assertions, de muchos tipos, es interesante. Pueden agregarlo por maven al proyecto, y en esta página http://joel-costigliola.github.io/assertj/ está el ejemplo de las funcionalidades.

Que tal amigos. Yo lo hice de esta manera.
Para los que no utilizamos assertTaht() 📚

MovieServiceShould.java

package com.platzi.javatests.movies.service;

import com.platzi.javatests.movies.data.MovieRepository;
import com.platzi.javatests.movies.model.Movie;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

import static com.platzi.javatests.movies.model.Genre.*;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class MovieServiceShould {

  @InjectMocks
  MovieService movieService;

  @Mock
  MovieRepository movieRepository;

  @Before
  public void setUp() {
    movieService = new MovieService(movieRepository);
    when(movieRepository.findAll()).thenReturn(Arrays.asList(
        new Movie(1, "Dark Knight", 152, ACTION),
        new Movie(2, "Memento", 113, THRILLER),
        new Movie(3, "There's Something About Mary", 119, COMEDY),
        new Movie(4, "Super 8", 112, THRILLER),
        new Movie(5, "Scream", 111, HORROR),
        new Movie(6, "Home Alone", 103, COMEDY),
        new Movie(7, "Matrix", 136, ACTION)
    ));
  }

  @Test
  public void returnMoviesByGenre() {
//    MovieRepository movieRepository = Mockito.mock(MovieRepository.class);
    Collection<Movie> movies = movieService.findMoviesByGenre(COMEDY);
    List<Integer> movieIds = movies.stream().map(Movie::getId).collect(Collectors.toList());

    assertThat(movieIds, is(Arrays.asList(3, 6)));
  }
}

MovieRepository.java

package com.platzi.javatests.movies.data;

import com.platzi.javatests.movies.model.Movie;

import java.util.Collection;

public interface MovieRepository {

  Movie findById(long id);

  Collection<Movie> findAll();

  void saveOrUpdate(Movie movie);
}

Genre.java

package com.platzi.javatests.movies.model;

public enum Genre {
  ACTION, COMEDY, DRAMA, HORROR, THRILLER
}

Movie.java

package com.platzi.javatests.movies.model;

public class Movie {

  private Integer id;
  private String name;
  private int minutes;
  private Genre genre;

  public Movie(String name, int minutes, Genre genre) {
    // this: call the second constructor.
    this(null, name, minutes, genre);
  }

  public Movie(Integer id, String name, int minutes, Genre genre) {
    this.id = id;
    this.name = name;
    this.minutes = minutes;
    this.genre = genre;
  }

  public Integer getId() {
    return id;
  }

  public String getName() {
    return name;
  }

  public int getMinutes() {
    return minutes;
  }

  public Genre getGenre() {
    return genre;
  }
}

MovieService.java

package com.platzi.javatests.movies.service;

import com.platzi.javatests.movies.data.MovieRepository;
import com.platzi.javatests.movies.model.Genre;
import com.platzi.javatests.movies.model.Movie;

import java.util.Collection;
import java.util.stream.Collectors;

public class MovieService {

  private MovieRepository movieRepository;

  public MovieService(MovieRepository movieRepository) {
    this.movieRepository = movieRepository;
  }

  public Collection<Movie> findMoviesByGenre(Genre genre) {
    return movieRepository.findAll().stream()
        .filter(movie -> movie.getGenre() == genre).collect(Collectors.toList());
  }
}

Considero que deberia haber un pdf de este curso par poderlo visualizar

Other way to evaluate the result instead of creating a new collection of id.
.
MovieServiceShould.java


    import static org.hamcrest.CoreMatchers.everyItem;
    import static org.hamcrest.CoreMatchers.is;
    import static org.hamcrest.beans.HasPropertyWithValue.hasProperty;
    import static org.junit.Assert.assertThat;

    ...

    @Test
    public void return_by_genre() {
        // arrange
        Mockito.when(this.movieRepository.findByGenre(EGenre.COMEDY))
                .thenReturn(Arrays.asList(...));
        // act
        List<Movie> listMovies = this.movieService.findByGenre(EGenre.COMEDY);
        // assert
        assertThat(listMovies, everyItem(hasProperty("genre", is(EGenre.COMEDY))));
    }

pom.xml

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-core</artifactId>
            <version>3.6.28</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.hamcrest</groupId>
            <artifactId>hamcrest-library</artifactId>
            <version>1.3</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

Quien guste estoy llevando el curso en este repositorio de git

Para utilizar el:
assertThat(moviesIds,is(Arrays.asList(1,2)));

Utilizar:
import static org.hamcrest.MatcherAssert.assertThat;

Para comparar cadenas serìa mejor usar Equals o EqualgnoreCase

Estupenda clase instructor Ferran y gracias por compartir esa manera de extraer datos de un Arreglo, no la conocía y voy a darle buen uso.

Con hasItems el orden de los items no se tendrá en cuenta.

        assertThat(movies.stream().map(movie -> movie.getId()).collect(Collectors.toList()), CoreMatchers.hasItems(6, 3));
Espectacular este curso. tan tan útil para el trabajo
Mi aporte public Collection\<Movie> findMoviesByGenre(Genre genre) { return movieRepository.findAll().stream().filter(movie -> movie.getGenre().equals(genre)).collect(Collectors.*toList*()); } Test @Test public void return\_movies\_by\_genre(){ MovieRepository movieRepository = Mockito.*mock*(MovieRepository.class); MovieService movieService = new MovieService(movieRepository); Mockito.*when*(movieRepository.findAll()).thenReturn(Arrays.*asList*( new Movie(1, "Dark Knight", 152, Genre.*ACTION*), new Movie(2, "Memento", 113, Genre.*THRILLER*), new Movie(3, "There's Something About Marty", 119, Genre.*COMEDY*), new Movie(4, "Super 8", 112, Genre.*THRILLER*), new Movie(5, "Scream", 111, Genre.*HORROR*), new Movie(6, "Home Alone", 103, Genre.*COMEDY*), new Movie(7, "Matrix", 136, Genre.*ACTION*), new Movie(8, "GhostBusters", 160, Genre.*THRILLER*), new Movie(9, "MythBusters", 151, Genre.*THRILLER*), new Movie(10, "DemonBusters", 195, Genre.*THRILLER*) )); Collection\<Movie> movies = movieService.findMoviesByGenre(Genre.*COMEDY*); List\<Integer> movieIds = movies.stream().map(Movie::getId).collect(Collectors.*toList*()); *assertThat*(movieIds, *is*(Arrays.*asList*(3,6)) ); }
The `assertThat()` method is `@deprecated` use: ```js import static org.junit.jupiter.api.Assertions.assertIterableEquals; ```Example: ```java @Test public void test_iterable() { // Arrange List<Integer> expectedList = Arrays.asList(1, 2, 3, 4, 5); List<Integer> actualList = Arrays.asList(1, 2, 3, 4, 5); // Assert assertArrayEquals(expectedList.toArray(), actualList.toArray()); assertIterableEquals(expectedList, actualList); } ```

Gran ejemplo! 😃

para los que quieren algo mas elavorado que regrese los que hagan un match de movie

    List<Movie> movieGenre = movies.stream().map(movie -> movie)
                .filter(fil -> fil.getGenre() == Genre.COMEDY)
                .collect(Collectors.toList());

        movieGenre.forEach(movie -> assertEquals(Genre.COMEDY, movie.getGenre()));

        assertEquals(2, movieGenre.size()); 

las ultimas clases vamos que si se puede

👌

Genial gracias 😃

Gracias

Increíble, muchas gracias.

Excelente aporte