Commit 09267cbc authored by Khalid Ali's avatar Khalid Ali

Added framework for tests and started adding models

parent e69b5996
......@@ -36,7 +36,10 @@ dependencies {
implementation('org.springframework.boot:spring-boot-starter-data-jpa')
implementation('org.springframework.boot:spring-boot-starter-data-rest')
implementation('org.springframework.boot:spring-boot-starter-web')
implementation('org.modelmapper:modelmapper:2.3.1')
compile group: 'org.postgresql', name: 'postgresql', version: '42.2.5'
compileOnly('org.projectlombok:lombok')
testImplementation('org.springframework.boot:spring-boot-starter-test')
testImplementation('org.assertj:assertj-core')
testImplementation('com.h2database:h2')
}
package com.gmu.bookshare;
import org.modelmapper.ModelMapper;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class BookshareApplication {
......@@ -9,4 +11,9 @@ public class BookshareApplication {
public static void main(String[] args) {
SpringApplication.run(BookshareApplication.class, args);
}
@Bean
public ModelMapper modelMapper() {
return new ModelMapper();
}
}
package com.gmu.bookshare.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.*;
import javax.persistence.*;
import java.util.Date;
......@@ -11,7 +9,9 @@ import java.util.Date;
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "bid", schema = "bookshare_schema")
@Table(name = "bid")
@Getter
@Setter
public class Bid {
@Id
......
package com.gmu.bookshare.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.*;
import javax.persistence.*;
import java.util.Date;
@Data
@NoArgsConstructor
@RequiredArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "listing", schema = "bookshare_schema")
public class Listing {
@Getter
@Setter
@Table(name = "listing")
public class ListingEntity {
@Id
@GeneratedValue
......@@ -22,15 +23,18 @@ public class Listing {
@Column(name = "course")
private String course;
@NonNull
@Column(name = "isbn")
private int isbn;
@NonNull
@Column(name = "condition")
private int condition;
@Column(name = "accessCode")
private boolean accessCode;
@NonNull
@Column(name = "price")
private double price;
......@@ -40,15 +44,19 @@ public class Listing {
@Column(name = "description")
private String description;
@NonNull
@Column(name = "createDate")
private Date createDate;
@NonNull
@Column(name = "bid_id")
private Long[] bid_id;
private Long bid_id;
@NonNull
@Column(name = "owner")
private Long owner;
@NonNull
@Column(name = "title")
private String title;
}
......@@ -2,6 +2,7 @@ package com.gmu.bookshare.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.Getter;
import lombok.NoArgsConstructor;
import javax.persistence.*;
......@@ -11,6 +12,7 @@ import javax.persistence.*;
@AllArgsConstructor
@Entity
@Table(name = "user")
@Getter
public class ShareUser {
@Id
......
package com.gmu.bookshare.error;
public class ListingNotFoundException extends RuntimeException {
public ListingNotFoundException(Long id) {
super("Could not find listing " + id);
}
}
package com.gmu.bookshare.model;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
@Data
@Getter
@Setter
public class ListingDto {
private static final SimpleDateFormat dateFormat
= new SimpleDateFormat("yyyy-MM-dd HH:mm");
private Long id;
private String course;
private int isbn;
private int condition;
private boolean accessCode;
private double price;
private byte[] image;
private String description;
private String createDate;
private String title;
public Date getCreateDateConverted(String timezone) throws ParseException {
dateFormat.setTimeZone(TimeZone.getTimeZone(timezone));
return dateFormat.parse(this.createDate);
}
public void setCreateDate(Date date) {
this.createDate = dateFormat.format(date);
}
}
package com.gmu.bookshare.persistence;
import com.gmu.bookshare.entity.Listing;
import org.springframework.data.repository.CrudRepository;
import com.gmu.bookshare.entity.ListingEntity;
import org.springframework.data.jpa.repository.JpaRepository;
public interface ListingRepository extends CrudRepository<Listing, Long> {
import java.util.List;
public interface ListingRepository extends JpaRepository<ListingEntity, Long> {
List<ListingEntity> findByTitle(String s);
List<ListingEntity> findByIsbn(int isbn);
}
package com.gmu.bookshare.service;
import com.gmu.bookshare.entity.ListingEntity;
import com.gmu.bookshare.error.ListingNotFoundException;
import com.gmu.bookshare.persistence.ListingRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class ListingService {
......@@ -13,4 +17,23 @@ public class ListingService {
public ListingService(ListingRepository listingRepository) {
this.listingRepository = listingRepository;
}
public List<ListingEntity> getAll() {
return listingRepository.findAll();
}
public ListingEntity addListing(ListingEntity newListingEntity) {
return listingRepository.save(newListingEntity);
}
public ListingEntity getById(Long id) {
return listingRepository.findById(id)
.orElseThrow(() -> new ListingNotFoundException(id));
}
public ListingEntity getIsbn(int isbn) {
return listingRepository.findByIsbn(isbn).get(0);
}
}
package com.gmu.bookshare.web;
import com.gmu.bookshare.entity.ListingEntity;
import com.gmu.bookshare.model.ListingDto;
import com.gmu.bookshare.service.BidService;
import com.gmu.bookshare.service.ListingService;
import com.gmu.bookshare.service.ShareUserService;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
@Controller
import java.text.ParseException;
import java.util.List;
import java.util.stream.Collectors;
@RestController
@RequestMapping("/bs/api/")
public class BookshareApiController {
private final ListingService listingService;
private final BidService bidService;
private final ShareUserService shareUserService;
@Autowired
private ModelMapper modelMapper;
@Autowired
public BookshareApiController(ListingService listingService, BidService bidService, ShareUserService shareUserService) {
this.listingService = listingService;
this.bidService = bidService;
this.shareUserService = shareUserService;
}
@GetMapping(value = "/listing/")
List<ListingDto> getListings() {
List<ListingEntity> listings = listingService.getAll();
return listings.stream()
.map(this::convertToDto)
.collect(Collectors.toList());
}
@PostMapping(value = "/listing/", consumes = "application/json")
ListingEntity newListing(@RequestBody ListingEntity newListingEntity) {
return listingService.addListing(newListingEntity);
}
@GetMapping(value = "/listing/{id}")
ListingEntity getOne(@PathVariable Long id) {
return listingService.getById(id);
}
private ListingDto convertToDto(ListingEntity listingEntity) {
ListingDto listingDto = modelMapper.map(listingEntity, ListingDto.class);
listingDto.setCreateDate(listingEntity.getCreateDate());
return listingDto;
}
private ListingEntity convertToEntity(ListingDto listingDto) throws ParseException {
ListingEntity post = modelMapper.map(listingDto, ListingEntity.class);
// post.setCreateDate(ListingDto.getCreateDateConverted(
// userService.getCurrentUser().getPreference().getTimezone()));
//
// if (ListingDto.getId() != null) {
// ListingEntity oldPost = listingService.getPostById(postDto.getId());
// post.setRedditID(oldPost.getRedditID());
// post.setSent(oldPost.isSent());
// }
return post;
}
}
......@@ -3,4 +3,4 @@ spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQL94Dialec
spring.datasource.url=jdbc:postgresql://localhost:26257/testdb?sslmode=disable
spring.jpa.show-sql=true
spring.datasource.username=user17
spring.datasource.password=
\ No newline at end of file
spring.datasource.password=
/*
CockroachDB Data Transfer
CockroachDB Setup
*/
DROP TABLE IF EXISTS ShareUser;
create table ShareUser (
CREATE TABLE ShareUser (
id SERIAL PRIMARY KEY,
email varchar(255),
name varchar(255)
......
package com.gmu.bookshare;
import com.gmu.bookshare.entity.ListingEntity;
import com.gmu.bookshare.service.BidService;
import com.gmu.bookshare.service.ListingService;
import com.gmu.bookshare.service.ShareUserService;
import com.gmu.bookshare.web.BookshareApiController;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
import static org.mockito.BDDMockito.given;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringRunner.class)
@WebMvcTest(BookshareApiController.class)
public class BookshareRestControllerIntegrationTest {
@Autowired
private MockMvc mvc;
@MockBean
private ListingService listingService;
@MockBean
private BidService bidService;
@MockBean
private ShareUserService shareUserService;
@Test
public void givenListing_whenGetListings_thenReturnJsonArray()
throws Exception {
ListingEntity alex = new ListingEntity(123456, 3, 14.99,
new Date(), 192838079872L, 2879878394L, "Title Calc 3");
List<ListingEntity> allListingEntities = Arrays.asList(alex);
given(listingService.getAll()).willReturn(allListingEntities);
mvc.perform(get("/bs/api/listing")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$", hasSize(1)))
.andExpect(jsonPath("$[0].isbn", is(alex.getIsbn())));
}
}
package com.gmu.bookshare;
import com.gmu.bookshare.entity.ListingEntity;
import com.gmu.bookshare.persistence.ListingRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.ArrayList;
import static org.assertj.core.api.Assertions.assertThat;
@RunWith(SpringRunner.class)
@DataJpaTest
public class ListingEntityRepositoryIntegrationTest {
@Autowired
private TestEntityManager testEntityManager;
@Autowired
private ListingRepository listingRepository;
@Test
public void whenFindByIsbn_thenReturnListing() {
// given
ListingEntity alex = new ListingEntity();
testEntityManager.persist(alex);
testEntityManager.flush();
// when
ArrayList<ListingEntity> found = (ArrayList<ListingEntity>) listingRepository.findByIsbn(alex.getIsbn());
// then
assertThat(found.get(0).getIsbn())
.isEqualTo(alex.getIsbn());
}
}
package com.gmu.bookshare;
import com.gmu.bookshare.entity.ListingEntity;
import com.gmu.bookshare.persistence.ListingRepository;
import com.gmu.bookshare.service.ListingService;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.ArrayList;
import java.util.Date;
import static org.assertj.core.api.Assertions.assertThat;
@RunWith(SpringRunner.class)
@SpringBootTest
public class ListingEntityServiceIntegrationTest {
@MockBean
private ListingRepository listingRepository;
@Autowired
private ListingService listingService;
@Before
public void setUp() {
ListingEntity listingEntity1 = new ListingEntity(123456, 3, 14.99,
new Date(), 192838079872L, 2879878394L, "Title Calc 3");
ArrayList<ListingEntity> l = new ArrayList<>();
l.add(listingEntity1);
Mockito.when(listingRepository.findByIsbn(listingEntity1.getIsbn()))
.thenReturn(l);
}
@Test
public void whenValidIsbn_thenListingShouldBeFound() {
int isbn = 123456;
ListingEntity found = listingService.getIsbn(isbn);
assertThat(found.getIsbn())
.isEqualTo(isbn);
}
}
spring.jpa.hibernate.ddl-auto=create
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment