Commit e832b39f authored by Khalid Ali's avatar Khalid Ali
Browse files

PUT request test added and other small changes.

parent 1b1ea997
...@@ -44,6 +44,9 @@ dependencies { ...@@ -44,6 +44,9 @@ dependencies {
implementation('org.springframework.boot:spring-boot-starter-data-jpa') 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-data-rest')
implementation('org.springframework.boot:spring-boot-starter-web') implementation('org.springframework.boot:spring-boot-starter-web')
implementation('org.springframework.boot:spring-boot-starter-actuator')
implementation('com.fasterxml.jackson.dataformat:jackson-dataformat-xml')
implementation('com.fasterxml.jackson.datatype:jackson-datatype-joda')
implementation('org.modelmapper:modelmapper:2.3.1') implementation('org.modelmapper:modelmapper:2.3.1')
compile group: 'org.postgresql', name: 'postgresql', version: '42.2.5' compile group: 'org.postgresql', name: 'postgresql', version: '42.2.5'
compileOnly('org.projectlombok:lombok') compileOnly('org.projectlombok:lombok')
......
package com.gmu.bookshare.model; package com.gmu.bookshare.model;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data; import lombok.Data;
import lombok.Getter; import lombok.NoArgsConstructor;
import lombok.Setter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date; import java.util.Date;
@Data @Data
@Getter @Builder
@Setter @NoArgsConstructor
@AllArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ListingDto { public class ListingDto {
private final SimpleDateFormat dateFormat // @Getter(AccessLevel.NONE)
= new SimpleDateFormat("yyyy-MM-dd HH:mm"); // @Setter(AccessLevel.NONE)
// private final SimpleDateFormat dateFormat
// = new SimpleDateFormat("yyyy-MM-dd HH:mm");
@JsonProperty("id")
private Long id; private Long id;
@JsonProperty("course")
private String course; private String course;
@JsonProperty("isbn")
private int isbn; private int isbn;
@JsonProperty("condition")
private int condition; private int condition;
@JsonProperty("accessCode")
private boolean accessCode; private boolean accessCode;
@JsonProperty("price")
private double price; private double price;
@JsonProperty("image")
private byte[] image; private byte[] image;
@JsonProperty("description")
private String description; private String description;
private String createDate; @JsonProperty("createDate")
private Date createDate;
@JsonProperty("title")
private String title; private String title;
public Date getCreateDateConverted() throws ParseException { // public Date getCreateDateConverted() throws ParseException {
return dateFormat.parse(this.createDate); // return dateFormat.parse(this.createDate);
} // }
//
public void setCreateDateConverted(Date date) { // public void setCreateDateConverted(Date date) {
this.createDate = dateFormat.format(date); // this.createDate = dateFormat.format(date);
} // }
} }
package com.gmu.bookshare.utils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.fasterxml.jackson.datatype.joda.JodaModule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.validation.constraints.NotNull;
import java.io.IOException;
public final class JsonUtil {
private static final Logger LOG = LoggerFactory.getLogger(JsonUtil.class);
private JsonUtil() {
}
/**
* Utility method to write json object as string.
*
* @param object - json obect
* @return - json string representing the object
*/
public static String writeValueAsString(@NotNull Object object) {
String jsonStr = "";
try {
jsonStr = getObjectMapperInstance().writeValueAsString(object);
} catch (JsonProcessingException pe) {
LOG.error("failed to create JSON String: {}", pe.getMessage());
}
return jsonStr;
}
/**
* Utility method to parse any json string and convert to java class.
*
* @param str - json string
* @param classType - target class type
* @param <T> - template
* @return - returns java object based on jason string
*/
public static <T> T parseString(@NotNull String str, Class<T> classType) {
ObjectMapper mapper = getObjectMapperInstance();
try {
return mapper.readValue(str, classType);
} catch (IOException exp) {
LOG.error("failed to parse JSON String: {}", exp.getMessage());
}
return null;
}
/**
* Get Object Mapper Instance.
*
* @return - ObjectMapper
*/
private static ObjectMapper getObjectMapperInstance() {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true);
mapper.enable(SerializationFeature.INDENT_OUTPUT);
mapper.registerModule(new JodaModule());
return mapper;
}
/**
* returns the mapper jackson xml mapper.
*/
public static XmlMapper getXmlMapperInstance() {
XmlMapper xmlMapper = new XmlMapper();
xmlMapper.setPropertyNamingStrategy(PropertyNamingStrategy.UPPER_CAMEL_CASE);
xmlMapper.enable(SerializationFeature.INDENT_OUTPUT);
return xmlMapper;
}
}
...@@ -12,7 +12,6 @@ import org.springframework.http.MediaType; ...@@ -12,7 +12,6 @@ import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import java.text.ParseException;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
...@@ -44,7 +43,7 @@ public class BookshareApiController { ...@@ -44,7 +43,7 @@ public class BookshareApiController {
@PostMapping(value = "/listing/", consumes = MediaType.APPLICATION_JSON_VALUE) @PostMapping(value = "/listing/", consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.CREATED) @ResponseStatus(HttpStatus.CREATED)
public ListingDto newListing(@RequestBody ListingDto listingDto) throws ParseException { public ListingDto newListing(@RequestBody ListingDto listingDto) {
ListingEntity post = convertToEntity(listingDto); ListingEntity post = convertToEntity(listingDto);
ListingEntity postCreated = listingService.addListing(post); ListingEntity postCreated = listingService.addListing(post);
return convertToDto(postCreated); return convertToDto(postCreated);
...@@ -56,7 +55,7 @@ public class BookshareApiController { ...@@ -56,7 +55,7 @@ public class BookshareApiController {
} }
@PutMapping(value = "/listing/{id}", produces = MediaType.APPLICATION_JSON_VALUE) @PutMapping(value = "/listing/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
ResponseEntity<ListingDto> updateListing(@RequestBody ListingDto listingDto) throws ParseException { ResponseEntity<ListingDto> updateListing(@RequestBody ListingDto listingDto) {
ListingEntity listingEntity = convertToEntity(listingDto); ListingEntity listingEntity = convertToEntity(listingDto);
ListingEntity ret = listingService.updateListing(listingEntity); ListingEntity ret = listingService.updateListing(listingEntity);
if (ret == null) { if (ret == null) {
...@@ -72,14 +71,10 @@ public class BookshareApiController { ...@@ -72,14 +71,10 @@ public class BookshareApiController {
} }
private ListingDto convertToDto(ListingEntity listingEntity) { private ListingDto convertToDto(ListingEntity listingEntity) {
ListingDto listingDto = modelMapper.map(listingEntity, ListingDto.class); return modelMapper.map(listingEntity, ListingDto.class);
listingDto.setCreateDateConverted(listingEntity.getCreateDate());
return listingDto;
} }
private ListingEntity convertToEntity(ListingDto listingDto) throws ParseException { private ListingEntity convertToEntity(ListingDto listingDto) {
ListingEntity post = modelMapper.map(listingDto, ListingEntity.class); return modelMapper.map(listingDto, ListingEntity.class);
post.setCreateDate(listingDto.getCreateDateConverted());
return post;
} }
} }
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQL94Dialect
spring.datasource.url=jdbc:postgresql://localhost:26257/testdb?sslmode=disable
spring.jpa.show-sql=true
spring.datasource.username=user17
spring.datasource.password=
spring.jpa:
hibernate.ddl-auto: update
properties.hibernate.dialect: org.hibernate.dialect.PostgreSQL94Dialect
show-sql: true
spring.datasource:
url: jdbc:postgresql://localhost:26257/testdb?sslmode=disable
username: user17
password:
server:
port: 9009
\ No newline at end of file
package com.gmu.bookshare; package com.gmu.bookshare;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.gmu.bookshare.entity.ListingEntity; import com.gmu.bookshare.entity.ListingEntity;
import com.gmu.bookshare.model.ListingDto; import com.gmu.bookshare.model.ListingDto;
import com.gmu.bookshare.service.BidService; import com.gmu.bookshare.service.BidService;
import com.gmu.bookshare.service.ListingService; import com.gmu.bookshare.service.ListingService;
import com.gmu.bookshare.service.ShareUserService; import com.gmu.bookshare.service.ShareUserService;
import com.gmu.bookshare.utils.JsonUtil;
import com.gmu.bookshare.web.BookshareApiController; import com.gmu.bookshare.web.BookshareApiController;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
...@@ -19,12 +17,13 @@ import org.springframework.http.MediaType; ...@@ -19,12 +17,13 @@ import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MockMvc;
import java.util.Arrays; import java.util.Collections;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.is;
import static org.hamcrest.collection.IsCollectionWithSize.hasSize; import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
...@@ -57,7 +56,7 @@ public class BookshareRestControllerIntegrationTest { ...@@ -57,7 +56,7 @@ public class BookshareRestControllerIntegrationTest {
ListingEntity alex = new ListingEntity(123456, 3, 14.99, ListingEntity alex = new ListingEntity(123456, 3, 14.99,
new Date(), 192838079872L, 2879878394L, "Title Calc 3"); new Date(), 192838079872L, 2879878394L, "Title Calc 3");
List<ListingEntity> allListingEntities = Arrays.asList(alex); List<ListingEntity> allListingEntities = Collections.singletonList(alex);
given(listingService.getAll()).willReturn(allListingEntities); given(listingService.getAll()).willReturn(allListingEntities);
...@@ -69,52 +68,46 @@ public class BookshareRestControllerIntegrationTest { ...@@ -69,52 +68,46 @@ public class BookshareRestControllerIntegrationTest {
} }
@Test @Test
public void givenListing_whenPutListings_thenReturnCorrectHttpStatus() public void givenListing_whenPutListing_thenReturnHttpOk()
throws Exception { throws Exception {
ListingEntity listingInDB = new ListingEntity(123456, 3, 14.99, ListingEntity listingInDB = new ListingEntity(123456, 3, 14.99,
new Date(), 192838079872L, 2879878394L, "Title Calc 3"); new Date(), 192838079872L, 2879878394L, "Title Calc 3");
ListingEntity listingNotInDB = new ListingEntity(123456, 3, 14.99, ListingEntity listingNotInDB = new ListingEntity(123456, 3, 14.99,
new Date(), 192838079872L, 2879878394L, "Title Calc 3"); new Date(), 192838079872L, 2879878394L, "Title Calc 3");
listingInDB.setId(123456L);
listingNotInDB.setId(123457L);
ListingDto listingDtoInDB = modelMapper.map(listingInDB, ListingDto.class); ListingDto listingDtoInDB = modelMapper.map(listingInDB, ListingDto.class);
listingDtoInDB.setCreateDateConverted(listingInDB.getCreateDate());
ListingDto listingDtoNotInDB = modelMapper.map(listingNotInDB, ListingDto.class); ListingDto listingDtoNotInDB = modelMapper.map(listingNotInDB, ListingDto.class);
listingDtoNotInDB.setCreateDateConverted(listingNotInDB.getCreateDate());
given(listingService.updateListing(any(ListingEntity.class))).willReturn(listingInDB);
// ListingDto listingDtoInDB = new ListingDto(); // given(listingService.updateListing(listingNotInDB)).willReturn(null);
// listingDtoInDB.setIsbn(123456);
// listingDtoInDB.setCondition(3); mvc.perform(put("/bs/api/listing/" + listingDtoInDB.getId())
// listingDtoInDB.setPrice(14.99);
// listingDtoInDB.setCreateDateConverted(new Date());
// listingDtoInDB.setTitle("Title Calc 3");
// listingDtoInDB.setId(listingInDB.getId());
//
// ListingDto listingDtoNotInDB = new ListingDto();
// listingDtoInDB.setIsbn(123456);
// listingDtoInDB.setCondition(3);
// listingDtoInDB.setPrice(14.99);
// listingDtoInDB.setCreateDateConverted(new Date());
// listingDtoInDB.setTitle("Title Calc 3");
// listingDtoInDB.setId(listingNotInDB.getId());
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter();
String requestJson = ow.writeValueAsString(listingDtoInDB);
String requestJson2 = ow.writeValueAsString(listingDtoNotInDB);
given(listingService.updateListing(listingInDB)).willReturn(listingInDB);
given(listingService.updateListing(listingNotInDB)).willReturn(null);
mvc.perform(put("/bs/api/listing/" + listingInDB.getId())
.contentType(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON)
.content(requestJson)) .content(JsonUtil.writeValueAsString(listingDtoInDB)))
.andExpect(status().isOk()); .andExpect(status().isOk());
mvc.perform(put("/bs/api/listing/" + listingNotInDB.getId()) // mvc.perform(put("/bs/api/listing/" + listingDtoNotInDB.getId())
// .contentType(MediaType.APPLICATION_JSON)
// .content(JsonUtil.writeValueAsString(listingDtoNotInDB)))
// .andExpect(status().isNotFound());
}
@Test
public void givenListing_whenPutInvalidListing_thenReturnHttpNotFound() throws Exception {
ListingEntity listingNotInDB = new ListingEntity(123456, 3, 14.99,
new Date(), 192838079872L, 2879878394L, "Title Calc 3");
listingNotInDB.setId(123457L);
ListingDto listingDtoNotInDB = modelMapper.map(listingNotInDB, ListingDto.class);
given(listingService.updateListing(any(ListingEntity.class))).willReturn(null);
mvc.perform(put("/bs/api/listing/" + listingDtoNotInDB.getId())
.contentType(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON)
.content(requestJson2)) .content(JsonUtil.writeValueAsString(listingDtoNotInDB)))
.andExpect(status().isNotFound()); .andExpect(status().isNotFound());
} }
} }
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