Skip to content

Instantly share code, notes, and snippets.

@darrenhaken
Created September 20, 2024 15:16
Show Gist options
  • Save darrenhaken/2edd14876adbc6a13b9a78af5926fc02 to your computer and use it in GitHub Desktop.
Save darrenhaken/2edd14876adbc6a13b9a78af5926fc02 to your computer and use it in GitHub Desktop.
package com.hannahhaken.dining_review.repository;
import com.hannahhaken.dining_review.model.User;
import jakarta.inject.Inject;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import org.hibernate.exception.ConstraintViolationException;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.test.context.ActiveProfiles;
import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.jupiter.api.Assertions.assertEquals;
@DataJpaTest
@ActiveProfiles("test")
public class UserRepositoryTest {
@Autowired
private UserRepository userRepository;
@PersistenceContext
private EntityManager entityManager;
@Test
public void can_create_and_retrieve_user() {
//given
User expectedUser = new User();
expectedUser.setUsername("Cloud Strife");
expectedUser.setCity("Manchester");
expectedUser.setCountry("England");
userRepository.save(expectedUser);
//when
User newUser = userRepository.findByUsername("Cloud Strife");
//then
assertThat("User ID should not be null", newUser.getId(), notNullValue());
assertEquals(expectedUser.getUsername(), newUser.getUsername());
assertEquals(expectedUser.getCity(), newUser.getCity());
assertEquals(expectedUser.getCountry(), newUser.getCountry());
}
@Test
public void whenSavingUser_shouldNotAllowMultipleUsersWithTheSameUsername() {
String duplicateUsername = "Cloud Strife";
User firstUser = testUser(duplicateUsername);
userRepository.save(firstUser);
entityManager.flush(); // Manually flush to apply changes
User duplicateUser = testUser(duplicateUsername);
userRepository.save(duplicateUser);
// Expect an exception when trying to save the second user
assertThatThrownBy(() -> entityManager.flush())
.isInstanceOf(ConstraintViolationException.class)
.hasMessageContaining("could not execute statement");
}
private User testUser(String username) {
User user = new User();
user.setUsername(username);
return user;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment