Kamishimi
Kamishimi
#boks Będzie remis mówię Wam
@test
void whenUserExist_DeleteUser() {
User user = userBuilder.buildById(1).build();
userSaver.save(user);
delete.deleteUserById(1);
assertThat(userChecker.userExist(1)).isFalse();
}
userSaver.save(user);
, to nie stanowi to problemu? Czy jakoś inaczej to zrobić?@Component
public class SessionChecker {
private final DataSource dataSource;
public SessionChecker(DataSource dataSource) {
this.dataSource = dataSource;
}
public boolean checkExistence(String sessionId) {
try {
String query = "SELECT COUNT(*) FROM sessions WHERE session_id = ?";
try (Connection connection = dataSource.getConnection();
PreparedStatement statement = connection.prepareStatement(query)) {
statement.setString(1, sessionId);
ResultSet resultSet = statement.executeQuery();
return resultSet.next() && resultSet.getInt(1) > 0;
}
} catch (SQLException e) {
private boolean checkExistence(String query, PreparedStatement statement)
. Wtedy każda z publicznych metodcheckExistence(String query, Consumer<PreparedStatement> propertySetter) {
try (Connection connection = dataSource.getConnection();
PreparedStatement statement = connection.prepareStatement(query)) {
propertySetter.accept(statement);
ResultSet resultSet = statement.executeQuery();
return resultSet.next() && resultSet.getInt(1) > 0;
} catch (SQLException e) {
throw new RuntimeException("Error during checking existence: " + e.getMessage(), e);
}
public boolean userHasActiveSession(int userId) {
String query = "SELECT COUNT(*) FROM sessions WHERE user_id = ?";
return checkExistence(query, st -> st.setInt(1, userId));
}
public boolean sessionExist(String sessionId)
@test
void whenUserExist_DeleteUserSessions() {
delete.deleteUserById(1);
assertThat(sessionChecker.hasActiveSession(1)).isFalse();
}
@test
void whenUserExist_DeleteUserSessions() {
int userId = 1;
delete.deleteUserById(1);
assertThat(sessionChecker.hasActiveSession(userId)).isFalse();
}
Nie tylko zmienne ale często nawet stałe.
A jak coś się powtarza w kilku miejscach, to dobrze jest stworzyć interface, w którym będziesz przechowywał stałe dostępne dla wszystkich testów w aplikacji
@test
void whenUserDeleted_SecondDeletionReturnNotFound() throws Exception {
Integer userId = idFetcher.fetchByUsername("Mark");
Cookie sessionId = auth.loginAdminUser();
mockMvc.perform(delete("/api/v1/users/" + userId).cookie(sessionId))
.andExpect(status().isOk());
mockMvc.perform(delete("/api/v1/users/" + userId).cookie(sessionId))
.andExpect(status().isNotFound());
}
mockMvc.perform(delete("/api/v1/users/" + userId).cookie(sessionId))
.andExpect(status().isOk());
Czy jest to bezpieczne?
@test
void whenLogoutSuccess_DeleteSession() throws Exception {
Cookie sessionCookie = logoutHelper.loginAndGetCookie();
String sessionId = tokenGenerator.generateHashedToken(sessionCookie.getValue());
mockMvc.perform(post("/api/v1/users/logout").cookie(sessionCookie))
.andExpect(status().isOk());
assertThat(session.sessionExist(sessionId)).isFalse();
}
@test
void whenLogoutSuccess_DeleteSession() throws Exception {
Cookie sessionCookie = logoutHelper.loginAndGetCookie();
String sessionId = tokenGenerator.generateHashedToken(sessionCookie.getValue());
assertThat(session.sessionExist(sessionId)).isTrue();
mockMvc.perform(post("/api/v1/users/logout").cookie(sessionCookie))
.andExpect(status().isOk());
assertThat(session.sessionExist(sessionId)).isFalse();
}
logoutHelper.loginAndGetCookie();
działa prawidłowo, co powinno być sprawdzone testami tej metody w klasie LogoutHelperTest
czy jakkolwiek się tam nazywa.@Component
public class DatabaseHelper {
private final DataSource dataSource;
public DatabaseHelper(DataSource dataSource) {
this.dataSource = dataSource;
}
public boolean userExist(String username) {
// kod
}
public boolean hasUserRole(String username, String roleName) {
// kod
}
}
UserDatabaseHelper
albo UserRepository
. W przeciwnym razie będą do niej trafiać wszystkie funkcjonalności bazodanowe, bo nazwa DatabaseHelper
jest bardzo pojemna i w dużym projekcie skończysz z ogromna klasą, która zwraca info o użytkownikach i wszystkim innym, co masz w projekcie.UserRepository
też nie jest za dużym konceptem. Pomocnicze @test
void whenEmailExist_ThrowException() {
assertException(() -> registration.register(registrationHelper.existEmail),
CredentialValidationException.class, "Email is already exist!.");
}
@test
void whenEmailExist_ThrowException() {
// given
RegisterRequest request = registrationHelper.existEmail;
// when & then
assertException(() -> registration.register(request),
CredentialValidationException.class, "Email is already exist!.");
}
@test
void whenEmailExist_ThrowException() {
// given
RegisterRequest request = registrationHelper.existEmail;
// when
Throwable result = catchThrowable((() -> registration.register(request))
//then
asserty z CredentialValidationException.class, "Email is already exist!.");
}
trzeba je wymieniać do 8h
public class RegistrationControllerHelper {
public static final String validCredentials =
"{\"username\": \"New\", \"email\": \"new@mail.com\", \"password\": \"Password#3\"}";
public static final String invalidCredentials =
"{\"username\": \"invalid\", \"email\": \"invalid\", \"password\": \"invalid\"}";
public static final String malformedRequest =
"{\"username\": \"New\", \"email\": \"new@mail.com\", \"password\": \"Password#3\"";
public static final String emptyCredentials =
"{\"username\": \"\", \"email\": \"\", \"password\": \"\"}";
}
new RegisterRequest("New", "new@mail.com", "Password#3");
.content(asJsonString(new EmployeeVO(null, "firstName4", "lastName4", "email4@mail.com")))
@Component
class CookieDeleterImpl implements CookieDeleter {
@OverRide
public void deleteCookie(HttpServletRequest request, HttpServletResponse response, String name) {
Cookie[] cookies = request.getCookies();
if (cookies != null) {
Arrays.stream(cookies)
.filter(cookie -> name.equals(cookie.getName()))
.forEach(cookie -> {
cookie.setValue(null);
cookie.setMaxAge(0);
cookie.setPath("/");
response.addCookie(cookie);
});
}
}
}
public class CookieDeleterImplTest {
private CookieDeleterImpl
Wykop.pl