Skip to content

Commit

Permalink
Merge pull request #10 from ONAV-KEA/tests
Browse files Browse the repository at this point in the history
added tests for UserService and EventService
  • Loading branch information
VictorHanert authored Dec 11, 2023
2 parents 442267e + 6539c31 commit 3d54845
Show file tree
Hide file tree
Showing 11 changed files with 275 additions and 12 deletions.
8 changes: 1 addition & 7 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -59,11 +59,6 @@
<version>4.13.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
Expand Down Expand Up @@ -99,9 +94,8 @@
<version>3.0.0-M5</version>
<configuration>
<includes>
<include>Sample.java</include>
<include>**/*Test.java</include>
</includes>

</configuration>
</plugin>
<plugin>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,15 +29,14 @@ public class InitData implements CommandLineRunner {

@Override
public void run(String... args) throws Exception {

List<Department> departments = new ArrayList<>();

if (departmentRepository.count() == 0) {
System.out.println("InitData.run: 2");
departments = createDepartments();
}

if (userRepository.count() == 0) {
if (!departments.isEmpty() && userRepository.count() == 0) {
System.out.println("InitData.run: 1");
createUsers(departments);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@
import lombok.NoArgsConstructor;
import lombok.Setter;

import java.util.HashSet;
import java.util.Set;

@Getter
@Setter
@NoArgsConstructor
@Entity
public class Department {
@Id
Expand All @@ -22,5 +22,9 @@ public class Department {
joinColumns = {@JoinColumn(name = "department_id")},
inverseJoinColumns = {@JoinColumn(name = "event_id")}
)
private Set<Event> events;
private Set<Event> events = new HashSet<>();

public Department() {
this.events = new HashSet<>();
}
}
8 changes: 7 additions & 1 deletion src/main/java/dk/kea/onav2ndproject_rest/entity/Event.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import lombok.Setter;

import java.time.LocalDate;
import java.util.HashSet;
import java.util.Set;

@Getter
Expand All @@ -35,5 +36,10 @@ public class Event {
private Set<UserEventDetails> userEventDetails;
@JsonBackReference
@ManyToMany(mappedBy = "events", cascade = {CascadeType.PERSIST, CascadeType.MERGE})
private Set<Department> departments;
private Set<Department> departments = new HashSet<>();

public Event(int id, String name) {
this.id = id;
this.name = name;
}
}
1 change: 1 addition & 0 deletions src/main/java/dk/kea/onav2ndproject_rest/entity/User.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
@Setter
@NoArgsConstructor
@Entity
@Table(name="usr")
@JsonIdentityInfo(
generator = ObjectIdGenerators.PropertyGenerator.class,
property = "id")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,12 @@ public class EventService {
@Autowired
UserRepository userRepository;

public EventService(EventRepository eventRepository, EventConverter eventConverter, DepartmentService departmentService) {
this.eventRepository = eventRepository;
this.eventConverter = eventConverter;
this.departmentService = departmentService;
}

public Page<EventDTO> getAllEvents(Pageable pageable) {
Page<Event> events = eventRepository.findAll(pageable);
return events.map(eventConverter::toDTO);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import dk.kea.onav2ndproject_rest.repository.UserEventDetailsRepository;
import dk.kea.onav2ndproject_rest.repository.UserRepository;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.crypto.password.PasswordEncoder;
Expand All @@ -23,6 +24,7 @@
import java.util.Set;

@AllArgsConstructor
@NoArgsConstructor
@Service
public class UserService implements IUserService{

Expand All @@ -31,6 +33,11 @@ public class UserService implements IUserService{
private UserConverter userConverter;
private UserEventDetailsRepository userEventDetailsRepository;

public UserService (UserRepository userRepository, UserConverter userConverter) {
this.userRepository = userRepository;
this.userConverter = userConverter;
}

public Page<UserDTO> getAllUsers(Pageable pageable) {
Page<User> users = userRepository.findAll(pageable);
return users.map(userConverter::toDTO);
Expand Down
1 change: 1 addition & 0 deletions src/main/resources/application.properties
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,5 @@ spring.datasource.username=${DATABASE_USERNAME}
spring.datasource.password=${DATABASE_PASSWORD}
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
#spring.h2.console.enabled=true
secret=${SECRET}
136 changes: 136 additions & 0 deletions src/test/java/dk/kea/onav2ndproject_rest/service/EventServiceTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
package dk.kea.onav2ndproject_rest.service;

import dk.kea.onav2ndproject_rest.dto.EventConverter;
import dk.kea.onav2ndproject_rest.dto.EventDTO;
import dk.kea.onav2ndproject_rest.entity.Department;
import dk.kea.onav2ndproject_rest.entity.Event;
import dk.kea.onav2ndproject_rest.exception.EventNotFoundException;
import dk.kea.onav2ndproject_rest.repository.DepartmentRepository;
import dk.kea.onav2ndproject_rest.repository.EventRepository;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.BeforeEach;
import org.mockito.ArgumentMatchers;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;

import java.util.*;

import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.doThrow;

@SpringBootTest
class EventServiceTest {

@Mock
private EventRepository mockedEventRepository;

EventService eventService;

@Autowired
EventConverter eventConverter;

@Mock
private DepartmentRepository mockedDepartmentRepository;

@Mock
private DepartmentService mockedDepartmentService;

@BeforeEach
void init(){
MockitoAnnotations.initMocks(this);
Event e1 = new Event();
e1.setId(1);
e1.setName("Event1");

Event e2 = new Event(
2,
"Event2"
);
List<Event> eventList = new ArrayList<>();

eventList.add(e1);
eventList.add(e2);

Page<Event> eventPage = new PageImpl<>(eventList);

Department department1 = new Department();
department1.setId(1);
department1.setName("IT");

Department department2 = new Department();
department2.setId(2);
department2.setName("Økonomi");

Mockito.when(mockedEventRepository.findAll(ArgumentMatchers.any(Pageable.class))).thenReturn(eventPage);
Mockito.when(mockedEventRepository.findById(1)).thenReturn(Optional.of(e1));
Mockito.when(mockedEventRepository.findById(42)).thenReturn(Optional.empty());
Mockito.when(mockedDepartmentRepository.findById(1)).thenReturn(Optional.of(department1));
Mockito.when(mockedDepartmentRepository.findById(2)).thenReturn(Optional.of(department2));
Mockito.when(mockedDepartmentService.findById(1)).thenReturn(Optional.of(department1));
Mockito.when(mockedDepartmentService.findById(2)).thenReturn(Optional.of(department2));
doThrow(new EventNotFoundException("Event not found with id: 42")).when(mockedEventRepository).deleteById(42);

Mockito.when(mockedEventRepository.save(ArgumentMatchers.any(Event.class))).thenAnswer(new Answer<Event>() {
@Override
public Event answer(InvocationOnMock invocation) throws Throwable {
Object[] arguments = invocation.getArguments();
if (arguments.length > 0 && arguments[0] instanceof Event) {
Event eventToSave = (Event) arguments[0];
if (eventToSave.getId()==0) {
eventToSave.setId(3);
}
return eventToSave;
} else {
throw new IllegalArgumentException("Invalid argument type");
}
}
});

eventService = new EventService(mockedEventRepository, eventConverter, mockedDepartmentService);
}

@Test
void getAllEvents() {
Page<EventDTO> eventDTOList = eventService.getAllEvents(Pageable.unpaged());
assertEquals("Event1", eventDTOList.get().findFirst().get().name());
assertEquals("Event2", eventDTOList.get().skip(1).findFirst().get().name());
}

@Test
void getEventById() {
EventDTO eventDTO = eventService.getEventById(1);
assertEquals("Event1", eventDTO.name());
assertThrows(EventNotFoundException.class, () -> eventService.getEventById(42));
}

@Test
void createEvent() {
Event event = new Event(0, "Event3");
event.setDepartments(new HashSet<>(Arrays.asList(mockedDepartmentService.findById(1).get(), mockedDepartmentService.findById(2).get())));
EventDTO resultEventDTO = eventService.createEvent(eventConverter.toDTO(event));
assertEquals(3, resultEventDTO.id());
}

@Test
void updateEvent() {
Event event = new Event(1, "UpdatedEvent");
event.setDepartments(new HashSet<>(Arrays.asList(mockedDepartmentService.findById(1).get(), mockedDepartmentService.findById(2).get())));
EventDTO resultEventDTO = eventService.updateEvent(1, eventConverter.toDTO(event));
assertEquals(1, resultEventDTO.id());
assertEquals("UpdatedEvent", resultEventDTO.name());
assertThrows(EventNotFoundException.class, () -> eventService.updateEvent(42, resultEventDTO));
}

@Test
void deleteEventById() {
assertThrows(EventNotFoundException.class, () -> eventService.deleteEventById(42));
}
}
107 changes: 107 additions & 0 deletions src/test/java/dk/kea/onav2ndproject_rest/service/UserServiceTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
package dk.kea.onav2ndproject_rest.service;

import dk.kea.onav2ndproject_rest.JwtTokenManager;
import dk.kea.onav2ndproject_rest.config.SecurityConfiguration;
import dk.kea.onav2ndproject_rest.dto.UserConverter;
import dk.kea.onav2ndproject_rest.entity.User;
import dk.kea.onav2ndproject_rest.exception.UserNotFoundException;
import dk.kea.onav2ndproject_rest.repository.UserRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentMatchers;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.stubbing.Answer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.util.List;

import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.doThrow;

@SpringBootTest
class UserServiceTest {
@Mock
private UserRepository mockedUserRepository;

UserService userService;

@Autowired
UserConverter userConverter;

@BeforeEach
void init(){
PasswordEncoder pw = SecurityConfiguration.passwordEncoder();
MockitoAnnotations.initMocks(this);
User u1 = new User();
u1.setId(1);
u1.setName("User1");
u1.setPassword(pw.encode("1234"));

User u2 = new User();
u2.setId(2);
u2.setName("User2");
u2.setPassword(pw.encode("1234"));

List<User> userList = List.of(u1, u2);

Mockito.when(mockedUserRepository.findAll()).thenReturn(userList);
Mockito.when(mockedUserRepository.findById(1)).thenReturn(java.util.Optional.of(u1));
Mockito.when(mockedUserRepository.findById(2)).thenReturn(java.util.Optional.of(u2));
doThrow(new UserNotFoundException("User does not exist with id: " + 3)).when(mockedUserRepository).findById(42);

Mockito.when(mockedUserRepository.save(ArgumentMatchers.any(User.class))).thenAnswer((Answer) invocation -> {
Object[] args = invocation.getArguments();
if (args.length > 0 && args[0] instanceof User){
User u = (User) args[0];
if(u.getId()==0){
u.setId(3);
}
return u;
} else{
throw new IllegalArgumentException("Wrong argument");
}
});

userService = new UserService(mockedUserRepository, userConverter);

}

@Test
void getAllUsers() {
assertEquals(2, userService.findAll().size());
}

@Test
void getUserById() {
assertEquals("User1", userService.findById(1).get().getName());
assertEquals("User2", userService.findById(2).get().getName());
assertThrows(UserNotFoundException.class, () -> userService.findById(42));
}

@Test
void createUser() {
PasswordEncoder pw = SecurityConfiguration.passwordEncoder();
User u3 = new User();
u3.setId(3);
u3.setName("User3");
u3.setPassword(pw.encode("1234"));
assertEquals(3, userService.save(u3).getId());
}

@Test
void deleteUser() {
User u3 = new User();
u3.setId(3);
u3.setName("User3");
userService.delete(u3);
assertEquals(2, userService.findAll().size());
assertThrows(UserNotFoundException.class, () -> userService.findById(42));
}



}
2 changes: 2 additions & 0 deletions src/test/resources/application.properties
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
spring.datasource.url=jdbc:h2:mem:test;MODE=MySQL
secret=onavkrergodtogjeghedderanderstellerogdenherkeyersimpelthengodhejhejhejhejhejhejhejhejhejhejhejhejhejhejhejhejhejhejhejhejhejhejhejhejhejhejhejhejhejhejhejhejhejhejhejhejhejhejhej

0 comments on commit 3d54845

Please sign in to comment.