diff --git a/pom.xml b/pom.xml index 802138e..91eb3b2 100644 --- a/pom.xml +++ b/pom.xml @@ -59,11 +59,6 @@ 4.13.2 test - - org.springframework.boot - spring-boot-starter-test - test - io.jsonwebtoken jjwt-impl @@ -99,9 +94,8 @@ 3.0.0-M5 - Sample.java + **/*Test.java - diff --git a/src/main/java/dk/kea/onav2ndproject_rest/config/InitData.java b/src/main/java/dk/kea/onav2ndproject_rest/config/InitData.java index 16082d3..cb6f814 100644 --- a/src/main/java/dk/kea/onav2ndproject_rest/config/InitData.java +++ b/src/main/java/dk/kea/onav2ndproject_rest/config/InitData.java @@ -29,7 +29,6 @@ public class InitData implements CommandLineRunner { @Override public void run(String... args) throws Exception { - List departments = new ArrayList<>(); if (departmentRepository.count() == 0) { @@ -37,7 +36,7 @@ public void run(String... args) throws Exception { departments = createDepartments(); } - if (userRepository.count() == 0) { + if (!departments.isEmpty() && userRepository.count() == 0) { System.out.println("InitData.run: 1"); createUsers(departments); } diff --git a/src/main/java/dk/kea/onav2ndproject_rest/entity/Department.java b/src/main/java/dk/kea/onav2ndproject_rest/entity/Department.java index f31d8cd..4e0f54b 100644 --- a/src/main/java/dk/kea/onav2ndproject_rest/entity/Department.java +++ b/src/main/java/dk/kea/onav2ndproject_rest/entity/Department.java @@ -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 @@ -22,5 +22,9 @@ public class Department { joinColumns = {@JoinColumn(name = "department_id")}, inverseJoinColumns = {@JoinColumn(name = "event_id")} ) - private Set events; + private Set events = new HashSet<>(); + + public Department() { + this.events = new HashSet<>(); + } } diff --git a/src/main/java/dk/kea/onav2ndproject_rest/entity/Event.java b/src/main/java/dk/kea/onav2ndproject_rest/entity/Event.java index d8bfc53..fad6d8a 100644 --- a/src/main/java/dk/kea/onav2ndproject_rest/entity/Event.java +++ b/src/main/java/dk/kea/onav2ndproject_rest/entity/Event.java @@ -10,6 +10,7 @@ import lombok.Setter; import java.time.LocalDate; +import java.util.HashSet; import java.util.Set; @Getter @@ -35,5 +36,10 @@ public class Event { private Set userEventDetails; @JsonBackReference @ManyToMany(mappedBy = "events", cascade = {CascadeType.PERSIST, CascadeType.MERGE}) - private Set departments; + private Set departments = new HashSet<>(); + + public Event(int id, String name) { + this.id = id; + this.name = name; + } } diff --git a/src/main/java/dk/kea/onav2ndproject_rest/entity/User.java b/src/main/java/dk/kea/onav2ndproject_rest/entity/User.java index 9fd16f9..2a75c33 100644 --- a/src/main/java/dk/kea/onav2ndproject_rest/entity/User.java +++ b/src/main/java/dk/kea/onav2ndproject_rest/entity/User.java @@ -16,6 +16,7 @@ @Setter @NoArgsConstructor @Entity +@Table(name="usr") @JsonIdentityInfo( generator = ObjectIdGenerators.PropertyGenerator.class, property = "id") diff --git a/src/main/java/dk/kea/onav2ndproject_rest/service/EventService.java b/src/main/java/dk/kea/onav2ndproject_rest/service/EventService.java index 145cbb7..cf3673b 100644 --- a/src/main/java/dk/kea/onav2ndproject_rest/service/EventService.java +++ b/src/main/java/dk/kea/onav2ndproject_rest/service/EventService.java @@ -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 getAllEvents(Pageable pageable) { Page events = eventRepository.findAll(pageable); return events.map(eventConverter::toDTO); diff --git a/src/main/java/dk/kea/onav2ndproject_rest/service/UserService.java b/src/main/java/dk/kea/onav2ndproject_rest/service/UserService.java index b9b5bed..1878078 100644 --- a/src/main/java/dk/kea/onav2ndproject_rest/service/UserService.java +++ b/src/main/java/dk/kea/onav2ndproject_rest/service/UserService.java @@ -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; @@ -23,6 +24,7 @@ import java.util.Set; @AllArgsConstructor +@NoArgsConstructor @Service public class UserService implements IUserService{ @@ -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 getAllUsers(Pageable pageable) { Page users = userRepository.findAll(pageable); return users.map(userConverter::toDTO); diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 27f2870..3ea1803 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -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} \ No newline at end of file diff --git a/src/test/java/dk/kea/onav2ndproject_rest/service/EventServiceTest.java b/src/test/java/dk/kea/onav2ndproject_rest/service/EventServiceTest.java new file mode 100644 index 0000000..3e1e854 --- /dev/null +++ b/src/test/java/dk/kea/onav2ndproject_rest/service/EventServiceTest.java @@ -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 eventList = new ArrayList<>(); + + eventList.add(e1); + eventList.add(e2); + + Page 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() { + @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 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)); + } +} \ No newline at end of file diff --git a/src/test/java/dk/kea/onav2ndproject_rest/service/UserServiceTest.java b/src/test/java/dk/kea/onav2ndproject_rest/service/UserServiceTest.java new file mode 100644 index 0000000..2a17e39 --- /dev/null +++ b/src/test/java/dk/kea/onav2ndproject_rest/service/UserServiceTest.java @@ -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 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)); + } + + + +} \ No newline at end of file diff --git a/src/test/resources/application.properties b/src/test/resources/application.properties new file mode 100644 index 0000000..9b07422 --- /dev/null +++ b/src/test/resources/application.properties @@ -0,0 +1,2 @@ +spring.datasource.url=jdbc:h2:mem:test;MODE=MySQL +secret=onavkrergodtogjeghedderanderstellerogdenherkeyersimpelthengodhejhejhejhejhejhejhejhejhejhejhejhejhejhejhejhejhejhejhejhejhejhejhejhejhejhejhejhejhejhejhejhejhejhejhejhejhejhejhej \ No newline at end of file