Curso de Spring Boot | 9. Tests unitarios con JUnit

Por 9.99€ al mes tendrás acceso completo a todos los cursos. Sin matrícula ni permanencia.

<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.8.1</version>
</dependency>
@Transactional // Esta anotación significa que las operación se realizarán contra la base de datos que utiliza la aplicación (y luego se desharán)
@SpringBootTest
class HelpinghandslocationApplicationTests {
	@Autowired
	private LocationRepository locationRepository;

	@Autowired
	private LocationController locationController;

	@Test // Esta anotación significa que el contenido de la anotación es un test
	@Order(1) // Podemos establecer el orden en el que se realizarán los tests (si no lo específicamos, el orden será aleatorio)
	void addLocationViaController(){
		LocationTagDTO testlocationTagDTO = new LocationTagDTO("Test Name1", 1.1,1.1, "Test Address1", List.of(2L,5L));
		assertNotNull(locationController.saveLocations(testlocationTagDTO).getBody(), "When saving the object, it needs to be returned");

		testlocationTagDTO =  new LocationTagDTO("Test Name2", 2.2,2.2, "Test Address2", List.of(2L,7L));
		assertNotNull(locationController.saveLocations(testlocationTagDTO).getBody(), "When saving the object, it needs to be returned");

	}

	@Test 
	@Order(2)
	void allLocationsReturnedWithoutTagIds(){
		long allRepositoryLocationsCount = locationRepository.count();
		assertTrue(allRepositoryLocationsCount>0, "Repository should have data!");

		List<Location> allControllerLocations = (List<Location>) locationController.getLocations(null).getBody();
		assertNotNull(allControllerLocations, "Controller should return a list");
		assertEquals(allRepositoryLocationsCount, allControllerLocations.size(), "Controller should return all locations");
	}

	@Test 
	@Order(3)
	void allLocationsHaveRequestedTags(){
		List <Long> requestedTagIds = List.of(2L, 5L);
		List<Location> allControllerLocations = (List<Location>) locationController.getLocations(requestedTagIds).getBody();
		assertNotNull(allControllerLocations, "Controller should return a list");

		allControllerLocations.forEach(location->{
			List<Tag> tags = location.getTags();
			List<Long> locationTagIds = tags.stream().map(Tag::getId).collect(Collectors.toList());
			assertTrue(locationTagIds.containsAll(requestedTagIds), "Location tags should include all requested tags");				
		});		
	}
}

Por 9.99€ al mes tendrás acceso completo a todos los cursos. Sin matrícula ni permanencia.