Skip to content
Projects
Groups
Snippets
Help
Loading...
Sign in
Toggle navigation
O
Orders
Project
Project
Details
Activity
Cycle Analytics
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Issues
0
Issues
0
List
Board
Labels
Milestones
Merge Requests
0
Merge Requests
0
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Charts
Create a new issue
Commits
Issue Boards
Open sidebar
Vladimir Trubachoff
Orders
Commits
b7d19978
Commit
b7d19978
authored
Jul 23, 2024
by
Vladimir Trubachoff
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
Added GoodsRepositoryTest, GoodsServiceTest, GoodsControllerTest
parent
6a036a07
Hide whitespace changes
Inline
Side-by-side
Showing
14 changed files
with
445 additions
and
69 deletions
+445
-69
build.gradle
build.gradle
+2
-1
Goods.java
src/main/java/com/example/testj/domain/Goods.java
+11
-7
RestErrorInfo.java
src/main/java/com/example/testj/domain/RestErrorInfo.java
+0
-11
GoodsService.java
src/main/java/com/example/testj/service/GoodsService.java
+2
-2
GoodsDto.java
src/main/java/com/example/testj/service/dto/GoodsDto.java
+7
-12
GoodsServiceImpl.java
...java/com/example/testj/service/impl/GoodsServiceImpl.java
+9
-11
GoodsMapper.java
...in/java/com/example/testj/service/mapper/GoodsMapper.java
+2
-1
GoodsController.java
...main/java/com/example/testj/web/rest/GoodsController.java
+13
-23
application-test.properties
src/main/resources/application-test.properties
+13
-0
application.properties
src/main/resources/application.properties
+1
-1
schema.sql
src/main/resources/schema.sql
+24
-0
GoodsRepositoryTest.java
...ava/com/example/testj/repository/GoodsRepositoryTest.java
+92
-0
GoodsServiceTest.java
...test/java/com/example/testj/service/GoodsServiceTest.java
+119
-0
GoodsControllerTest.java
.../java/com/example/testj/web/rest/GoodsControllerTest.java
+150
-0
No files found.
build.gradle
View file @
b7d19978
...
...
@@ -31,10 +31,11 @@ dependencies {
testCompileOnly
'org.projectlombok:lombok:1.18.34'
testAnnotationProcessor
'org.projectlombok:lombok:1.18.34'
implementation
'org.mapstruct:mapstruct:1.5.5.Final'
annotationProcessor
'org.mapstruct:mapstruct-processor:1.5.5.Final'
annotationProcessor
'org.projectlombok:lombok-mapstruct-binding:0.2.0'
annotationProcessor
'org.mapstruct:mapstruct-processor:1.5.5.Final'
}
tasks
.
named
(
'test'
)
{
useJUnitPlatform
()
jvmArgs
(
"-XX:+EnableDynamicAgentLoading"
)
}
src/main/java/com/example/testj/domain/Goods.java
View file @
b7d19978
package
com
.
example
.
testj
.
domain
;
import
jakarta.persistence.*
;
import
jakarta.validation.constraints.NotEmpty
;
import
jakarta.validation.constraints.NotBlank
;
import
jakarta.validation.constraints.Positive
;
import
lombok.AllArgsConstructor
;
import
lombok.Getter
;
import
lombok.
Required
ArgsConstructor
;
import
lombok.
No
ArgsConstructor
;
import
lombok.Setter
;
import
java.util.ArrayList
;
import
java.util.List
;
@Getter
@Setter
@RequiredArgsConstructor
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table
(
name
=
"goods"
)
public
class
Goods
{
...
...
@@ -19,14 +23,14 @@ public class Goods {
@Column
(
name
=
"id"
)
private
Long
id
;
@Not
Empty
@Not
Blank
@Column
(
name
=
"name"
)
private
String
name
;
@Positive
@Column
(
name
=
"price"
)
private
double
price
;
@OneToMany
(
mappedBy
=
"goods"
,
cascade
=
CascadeType
.
ALL
,
orphanRemoval
=
true
)
private
List
<
OrderLine
>
orderLines
;
@OneToMany
(
mappedBy
=
"goods"
,
fetch
=
FetchType
.
LAZY
,
cascade
=
CascadeType
.
ALL
)
private
List
<
OrderLine
>
orderLines
=
new
ArrayList
<>();
}
src/main/java/com/example/testj/domain/RestErrorInfo.java
deleted
100644 → 0
View file @
6a036a07
package
com
.
example
.
testj
.
domain
;
public
class
RestErrorInfo
{
public
final
String
detail
;
public
final
String
message
;
public
RestErrorInfo
(
Exception
ex
,
String
detail
)
{
this
.
message
=
ex
.
getLocalizedMessage
();
this
.
detail
=
detail
;
}
}
src/main/java/com/example/testj/service/GoodsService.java
View file @
b7d19978
...
...
@@ -5,11 +5,11 @@ import com.example.testj.service.dto.GoodsDto;
import
org.springframework.data.web.PagedModel
;
public
interface
GoodsService
{
PagedModel
<
GoodsDto
>
get
GoodsPaged
(
Integer
page
,
Integer
size
,
String
sortBy
,
String
sortDir
);
PagedModel
<
GoodsDto
>
get
PagedGoods
(
Integer
page
,
Integer
size
,
String
sortBy
,
String
sortDir
);
GoodsDto
getGoods
(
Long
id
);
GoodsDto
createOrUpdate
(
Goods
goods
);
GoodsDto
createOrUpdate
Goods
(
Goods
goods
);
void
deleteGoods
(
Long
id
);
}
src/main/java/com/example/testj/service/dto/GoodsDto.java
View file @
b7d19978
package
com
.
example
.
testj
.
service
.
dto
;
import
jakarta.validation.constraints.Digits
;
import
jakarta.validation.constraints.Min
;
import
jakarta.validation.constraints.NotEmpty
;
import
jakarta.validation.constraints.Positive
;
import
lombok.AllArgsConstructor
;
import
lombok.Getter
;
import
lombok.Setter
;
import
com.fasterxml.jackson.annotation.JsonInclude
;
import
jakarta.validation.constraints.*
;
import
lombok.*
;
import
java.io.Serializable
;
...
...
@@ -14,16 +10,16 @@ import java.io.Serializable;
* DTO for {@link com.example.testj.domain.Goods}
*/
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
@JsonInclude
(
JsonInclude
.
Include
.
NON_NULL
)
public
class
GoodsDto
implements
Serializable
{
private
final
Long
id
;
private
Long
id
;
@Not
Empty
@Not
Blank
private
String
name
;
@Min
(
0L
)
@Digits
(
integer
=
6
,
fraction
=
2
)
@Positive
private
double
price
;
}
\ No newline at end of file
src/main/java/com/example/testj/service/impl/GoodsServiceImpl.java
View file @
b7d19978
package
com
.
example
.
testj
.
service
.
impl
;
import
com.example.testj.domain.Goods
;
import
com.example.testj.exception.ResourceNotFoundException
;
import
com.example.testj.repository.GoodsRepository
;
import
com.example.testj.service.GoodsService
;
import
com.example.testj.service.dto.GoodsDto
;
import
com.example.testj.service.mapper.GoodsMapper
;
import
lombok.RequiredArgsConstructor
;
import
org.springframework.data.domain.PageRequest
;
...
...
@@ -8,37 +12,31 @@ import org.springframework.data.domain.Sort;
import
org.springframework.data.web.PagedModel
;
import
org.springframework.stereotype.Service
;
import
com.example.testj.domain.Goods
;
import
com.example.testj.exception.ResourceNotFoundException
;
import
com.example.testj.repository.GoodsRepository
;
import
com.example.testj.service.dto.GoodsDto
;
@Service
@RequiredArgsConstructor
public
class
GoodsServiceImpl
implements
GoodsService
{
private
final
GoodsRepository
goodsRepository
;
private
final
GoodsMapper
goodsMapper
;
@Override
public
PagedModel
<
GoodsDto
>
get
GoodsPaged
(
Integer
page
,
Integer
size
,
String
sortBy
,
String
sortDir
)
{
public
PagedModel
<
GoodsDto
>
get
PagedGoods
(
Integer
page
,
Integer
size
,
String
sortBy
,
String
sortDir
)
{
return
new
PagedModel
<>(
goodsRepository
.
findAll
(
PageRequest
.
of
(
page
,
size
,
Sort
.
by
(
Sort
.
Direction
.
fromString
(
sortDir
),
sortBy
)))
.
map
(
goodsMapper:
:
toDto
));
}
@Override
public
GoodsDto
getGoods
(
Long
id
)
{
return
goodsRepository
.
findById
(
id
).
map
(
goodsMapper:
:
toDto
).
orElse
(
null
);
public
GoodsDto
getGoods
(
Long
id
)
throws
ResourceNotFoundException
{
return
goodsRepository
.
findById
(
id
).
map
(
goodsMapper:
:
toDto
).
orElse
Throw
(
ResourceNotFoundException:
:
new
);
}
@Override
public
GoodsDto
createOrUpdate
(
Goods
goods
)
{
public
GoodsDto
createOrUpdate
Goods
(
Goods
goods
)
{
return
goodsMapper
.
toDto
(
this
.
goodsRepository
.
save
(
goods
));
}
@Override
public
void
deleteGoods
(
Long
id
)
{
public
void
deleteGoods
(
Long
id
)
throws
ResourceNotFoundException
{
this
.
goodsRepository
.
findById
(
id
).
orElseThrow
(
ResourceNotFoundException:
:
new
);
this
.
goodsRepository
.
deleteById
(
id
);
}
...
...
src/main/java/com/example/testj/service/mapper/GoodsMapper.java
View file @
b7d19978
...
...
@@ -3,8 +3,9 @@ package com.example.testj.service.mapper;
import
com.example.testj.domain.Goods
;
import
com.example.testj.service.dto.GoodsDto
;
import
org.mapstruct.Mapper
;
import
org.mapstruct.ReportingPolicy
;
@Mapper
(
componentModel
=
"spring"
)
@Mapper
(
componentModel
=
"spring"
,
unmappedTargetPolicy
=
ReportingPolicy
.
IGNORE
)
public
interface
GoodsMapper
{
GoodsDto
toDto
(
Goods
goods
);
Goods
toEntity
(
GoodsDto
dto
);
...
...
src/main/java/com/example/testj/web/rest/GoodsController.java
View file @
b7d19978
package
com
.
example
.
testj
.
web
.
rest
;
import
com.example.testj.exception.ResourceNotFoundException
;
import
com.example.testj.service.GoodsService
;
import
com.example.testj.service.dto.GoodsDto
;
import
com.example.testj.service.mapper.GoodsMapper
;
import
jakarta.validation.Valid
;
import
lombok.RequiredArgsConstructor
;
import
org.springframework.data.web.PagedModel
;
import
org.springframework.http.HttpStatus
;
import
org.springframework.http.ResponseEntity
;
import
org.springframework.web.bind.annotation.CrossOrigin
;
import
org.springframework.web.bind.annotation.DeleteMapping
;
import
org.springframework.web.bind.annotation.GetMapping
;
import
org.springframework.web.bind.annotation.PathVariable
;
import
org.springframework.web.bind.annotation.PostMapping
;
import
org.springframework.web.bind.annotation.PutMapping
;
import
org.springframework.web.bind.annotation.RequestBody
;
import
org.springframework.web.bind.annotation.RequestHeader
;
import
org.springframework.web.bind.annotation.RequestMapping
;
import
org.springframework.web.bind.annotation.ResponseStatus
;
import
org.springframework.web.bind.annotation.RestController
;
import
com.example.testj.exception.ResourceNotFoundException
;
import
com.example.testj.service.GoodsService
;
import
com.example.testj.service.dto.GoodsDto
;
import
org.springframework.web.bind.annotation.*
;
@RestController
@RequestMapping
(
"/api/goods"
)
...
...
@@ -30,35 +20,35 @@ public class GoodsController {
private
final
GoodsMapper
goodsMapper
;
@GetMapping
public
PagedModel
<
GoodsDto
>
g
oods
(
public
PagedModel
<
GoodsDto
>
g
etPaged
(
@RequestHeader
(
name
=
"X-Page-Current"
,
defaultValue
=
"0"
)
Integer
page
,
@RequestHeader
(
name
=
"X-Page-Size"
,
defaultValue
=
"10"
)
Integer
size
,
@RequestHeader
(
name
=
"X-Sort-By"
,
defaultValue
=
"id"
)
String
sortBy
,
@RequestHeader
(
name
=
"X-Sort-Direction"
,
defaultValue
=
"ASC"
)
String
sortDir
)
{
return
goodsService
.
get
GoodsPaged
(
page
,
size
,
sortBy
,
sortDir
);
return
goodsService
.
get
PagedGoods
(
page
,
size
,
sortBy
,
sortDir
);
}
@GetMapping
(
"/{id}"
)
public
GoodsDto
g
oods
(
@PathVariable
Long
id
)
{
public
GoodsDto
g
et
(
@PathVariable
Long
id
)
{
return
goodsService
.
getGoods
(
id
);
}
@PostMapping
@ResponseStatus
(
HttpStatus
.
CREATED
)
public
GoodsDto
create
Goods
(
@RequestBody
GoodsDto
goods
)
{
return
this
.
goodsService
.
createOrUpdate
(
goodsMapper
.
toEntity
(
goods
));
public
GoodsDto
create
(
@Valid
@RequestBody
GoodsDto
goods
)
{
return
this
.
goodsService
.
createOrUpdate
Goods
(
goodsMapper
.
toEntity
(
goods
));
}
@PutMapping
(
"/{id}"
)
public
GoodsDto
update
Goods
(
@PathVariable
Long
id
,
@RequestBody
GoodsDto
goods
)
{
public
GoodsDto
update
(
@PathVariable
Long
id
,
@Valid
@RequestBody
GoodsDto
goods
)
{
GoodsDto
updatedGoods
=
goodsService
.
getGoods
(
id
);
updatedGoods
.
setName
(
goods
.
getName
());
updatedGoods
.
setPrice
(
goods
.
getPrice
());
return
this
.
goodsService
.
createOrUpdate
(
goodsMapper
.
toEntity
(
updatedGoods
));
return
this
.
goodsService
.
createOrUpdate
Goods
(
goodsMapper
.
toEntity
(
updatedGoods
));
}
@DeleteMapping
(
"/{id}"
)
public
ResponseEntity
<
HttpStatus
>
delete
Goods
(
@PathVariable
Long
id
)
{
public
ResponseEntity
<
HttpStatus
>
delete
(
@PathVariable
Long
id
)
{
try
{
goodsService
.
deleteGoods
(
id
);
return
new
ResponseEntity
<>(
HttpStatus
.
OK
);
...
...
src/main/resources/application-test.properties
0 → 100644
View file @
b7d19978
spring.application.name
=
testj
spring.datasource.url
=
jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1
spring.datasource.driverClassName
=
org.h2.Driver
spring.datasource.username
=
sa
spring.datasource.password
=
spring.jpa.database-platform
=
org.hibernate.dialect.H2Dialect
spring.jpa.properties.hibernate.dialect
=
org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto
=
update
spring.jpa.properties.hibernate.show_sql
=
true
spring.jpa.properties.hibernate.format_sql
=
true
\ No newline at end of file
src/main/resources/application.properties
View file @
b7d19978
spring.application.name
=
testj
spring.datasource.url
=
jdbc:h2:mem:
test
db
spring.datasource.url
=
jdbc:h2:mem:
main
db
spring.datasource.driverClassName
=
org.h2.Driver
spring.jpa.hibernate.ddl-auto
=
create-drop
spring.jpa.defer-datasource-initialization
=
true
...
...
src/main/resources/schema.sql
0 → 100644
View file @
b7d19978
create
table
if
not
exists
orders
(
id
INT
,
client
VARCHAR
(
50
),
date
DATE
,
address
VARCHAR
(
50
),
PRIMARY
KEY
(
id
)
);
create
table
if
not
exists
goods
(
id
INT
,
name
VARCHAR
(
50
),
price
DECIMAL
(
5
,
2
),
PRIMARY
KEY
(
id
)
);
create
table
if
not
exists
order_line
(
id
INT
,
order_id
INT
,
goods_id
INT
,
count
INT
,
PRIMARY
KEY
(
id
),
FOREIGN
KEY
(
order_id
)
REFERENCES
orders
(
id
),
FOREIGN
KEY
(
goods_id
)
REFERENCES
goods
(
id
)
);
src/test/java/com/example/testj/repository/GoodsRepositoryTest.java
0 → 100644
View file @
b7d19978
package
com
.
example
.
testj
.
repository
;
import
com.example.testj.domain.Goods
;
import
org.junit.jupiter.api.Order
;
import
org.junit.jupiter.api.Test
;
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.ActiveProfiles
;
import
java.util.List
;
import
java.util.stream.StreamSupport
;
import
static
org
.
junit
.
jupiter
.
api
.
Assertions
.*;
@DataJpaTest
@ActiveProfiles
(
"test"
)
public
class
GoodsRepositoryTest
{
@Autowired
private
GoodsRepository
goodsRepository
;
@Autowired
private
TestEntityManager
entityManager
;
@Test
void
testFindById
()
{
// given
Long
id
=
1L
;
// when
Goods
found
=
goodsRepository
.
findById
(
id
).
orElse
(
null
);
// then
assertNotNull
(
found
);
assertEquals
(
id
,
found
.
getId
());
}
@Test
void
testFindByIdNotFound
()
{
// given
Long
id
=
999L
;
// when
Goods
found
=
goodsRepository
.
findById
(
id
).
orElse
(
null
);
// then
assertNull
(
found
);
}
@Test
@Order
(
0
)
void
testFindAll
()
{
// when
List
<
Goods
>
found
=
StreamSupport
.
stream
(
goodsRepository
.
findAll
().
spliterator
(),
false
).
toList
();
// then
assertNotNull
(
found
);
assertEquals
(
100
,
found
.
size
());
}
@Test
void
testSave
()
{
// given
Goods
goods
=
new
Goods
();
goods
.
setName
(
"new product"
);
goods
.
setPrice
(
10.99f
);
// when
Goods
inserted
=
goodsRepository
.
save
(
goods
);
// then
assertNotNull
(
inserted
);
assertEquals
(
entityManager
.
find
(
Goods
.
class
,
inserted
.
getId
()),
inserted
);
}
@Test
void
testUpdate
()
{
// given
Long
id
=
1L
;
Goods
goods
=
entityManager
.
find
(
Goods
.
class
,
id
);
goods
.
setId
(
id
);
goods
.
setName
(
"product 2"
);
goods
.
setPrice
(
1.99f
);
// when
Goods
updated
=
goodsRepository
.
save
(
goods
);
// then
assertNotNull
(
updated
);
assertEquals
(
entityManager
.
find
(
Goods
.
class
,
updated
.
getId
()),
updated
);
}
@Test
void
testDeleteById
()
{
// given
Long
id
=
1L
;
// when
goodsRepository
.
deleteById
(
id
);
// then
assertNull
(
entityManager
.
find
(
Goods
.
class
,
id
));
}
}
src/test/java/com/example/testj/service/GoodsServiceTest.java
0 → 100644
View file @
b7d19978
package
com
.
example
.
testj
.
service
;
import
com.example.testj.domain.Goods
;
import
com.example.testj.repository.GoodsRepository
;
import
com.example.testj.service.dto.GoodsDto
;
import
com.example.testj.service.impl.GoodsServiceImpl
;
import
com.example.testj.service.mapper.GoodsMapper
;
import
org.junit.jupiter.api.Test
;
import
org.junit.jupiter.api.extension.ExtendWith
;
import
org.mapstruct.factory.Mappers
;
import
org.mockito.InjectMocks
;
import
org.mockito.Mock
;
import
org.mockito.Spy
;
import
org.mockito.junit.jupiter.MockitoExtension
;
import
org.springframework.data.domain.PageImpl
;
import
org.springframework.data.domain.Pageable
;
import
org.springframework.data.web.PagedModel
;
import
java.util.List
;
import
java.util.Optional
;
import
java.util.stream.Stream
;
import
static
org
.
junit
.
jupiter
.
api
.
Assertions
.
assertEquals
;
import
static
org
.
junit
.
jupiter
.
api
.
Assertions
.
assertNotNull
;
import
static
org
.
mockito
.
Mockito
.*;
@ExtendWith
(
MockitoExtension
.
class
)
public
class
GoodsServiceTest
{
@InjectMocks
private
GoodsServiceImpl
goodsService
;
@Mock
private
GoodsRepository
goodsRepository
;
@Spy
private
final
GoodsMapper
goodsMapper
=
Mappers
.
getMapper
(
GoodsMapper
.
class
);
private
final
List
<
Goods
>
goodsList
=
Stream
.
of
(
new
GoodsDto
(
1L
,
"product #1"
,
99.99f
),
new
GoodsDto
(
2L
,
"product #2"
,
25.99f
),
new
GoodsDto
(
3L
,
"product #3"
,
3.5f
),
new
GoodsDto
(
4L
,
"product #4"
,
60
f
),
new
GoodsDto
(
5L
,
"product #5"
,
10.1f
)
).
map
(
goodsMapper:
:
toEntity
).
toList
();
@Test
void
testGetGoods
()
{
// given
Long
id
=
1L
;
// when
when
(
goodsRepository
.
findById
(
id
)).
thenReturn
(
Optional
.
of
(
goodsList
.
getFirst
()));
GoodsDto
goodsDto
=
goodsService
.
getGoods
(
id
);
// then
assertEquals
(
id
,
goodsDto
.
getId
());
verify
(
goodsRepository
,
times
(
1
)).
findById
(
id
);
}
@Test
void
testGetPagedGoods
()
{
// when
when
(
goodsRepository
.
findAll
(
any
(
Pageable
.
class
))).
thenReturn
(
new
PageImpl
<>(
goodsList
));
PagedModel
<
GoodsDto
>
goodsDtoPagedModel
=
goodsService
.
getPagedGoods
(
1
,
10
,
"id"
,
"ASC"
);
// then
assertNotNull
(
goodsDtoPagedModel
);
assertEquals
(
goodsDtoPagedModel
.
getContent
().
size
(),
5
);
verify
(
goodsRepository
,
times
(
1
)).
findAll
(
any
(
Pageable
.
class
));
}
@Test
void
testUpdateGoods
()
{
// given
Goods
goods
=
goodsList
.
getFirst
();
goods
.
setName
(
"updated #1"
);
goods
.
setPrice
(
1.5f
);
// when
when
(
goodsRepository
.
save
(
goods
)).
thenReturn
(
goods
);
GoodsDto
updated
=
goodsService
.
createOrUpdateGoods
(
goods
);
// then
assertNotNull
(
updated
);
assertEquals
(
goods
.
getId
(),
updated
.
getId
());
assertEquals
(
goods
.
getPrice
(),
updated
.
getPrice
());
assertEquals
(
goods
.
getName
(),
updated
.
getName
());
verify
(
goodsRepository
,
only
()).
save
(
any
());
}
@Test
void
testCreateGoods
()
{
// given
Goods
goods
=
new
Goods
();
goods
.
setName
(
"New Product"
);
goods
.
setPrice
(
99.99f
);
Goods
result
=
new
Goods
();
Long
goodsNextId
=
goodsList
.
getLast
().
getId
()
+
1
;
result
.
setId
(
goodsNextId
);
result
.
setName
(
goods
.
getName
());
result
.
setPrice
(
goods
.
getPrice
());
// when
when
(
goodsRepository
.
save
(
goods
)).
thenReturn
(
result
);
GoodsDto
created
=
goodsService
.
createOrUpdateGoods
(
goods
);
// then
assertNotNull
(
goods
);
assertEquals
(
goodsNextId
,
created
.
getId
());
assertEquals
(
created
.
getName
(),
goods
.
getName
());
assertEquals
(
created
.
getPrice
(),
99.99f
);
verify
(
goodsRepository
,
only
()).
save
(
any
());
}
@Test
void
testDeleteGoods
()
{
// given
Long
id
=
1L
;
// when
when
(
goodsRepository
.
findById
(
id
)).
thenReturn
(
Optional
.
of
(
goodsList
.
getFirst
()));
doNothing
().
when
(
goodsRepository
).
deleteById
(
id
);
goodsService
.
deleteGoods
(
id
);
// then
verify
(
goodsRepository
,
times
(
1
)).
deleteById
(
id
);
}
}
src/test/java/com/example/testj/web/rest/GoodsControllerTest.java
0 → 100644
View file @
b7d19978
package
com
.
example
.
testj
.
web
.
rest
;
import
com.example.testj.exception.ResourceNotFoundException
;
import
com.example.testj.service.GoodsService
;
import
com.example.testj.service.dto.GoodsDto
;
import
com.example.testj.service.mapper.GoodsMapper
;
import
com.fasterxml.jackson.databind.ObjectMapper
;
import
org.json.JSONObject
;
import
org.junit.jupiter.api.DisplayName
;
import
org.junit.jupiter.api.Test
;
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.data.domain.Page
;
import
org.springframework.data.domain.PageImpl
;
import
org.springframework.data.domain.PageRequest
;
import
org.springframework.data.web.PagedModel
;
import
org.springframework.http.MediaType
;
import
org.springframework.test.web.servlet.MockMvc
;
import
java.util.List
;
import
java.util.stream.Stream
;
import
static
org
.
mockito
.
Mockito
.*;
import
static
org
.
springframework
.
test
.
web
.
servlet
.
request
.
MockMvcRequestBuilders
.*;
import
static
org
.
springframework
.
test
.
web
.
servlet
.
result
.
MockMvcResultMatchers
.
jsonPath
;
import
static
org
.
springframework
.
test
.
web
.
servlet
.
result
.
MockMvcResultMatchers
.
status
;
//@SpringBootTest
//@AutoConfigureMockMvc
@WebMvcTest
(
GoodsController
.
class
)
public
class
GoodsControllerTest
{
@Autowired
private
MockMvc
mvc
;
@MockBean
private
GoodsService
goodsService
;
@MockBean
private
GoodsMapper
goodsMapper
;
private
final
List
<
GoodsDto
>
goodsList
=
Stream
.
of
(
new
GoodsDto
(
1L
,
"product 1"
,
9.99f
),
new
GoodsDto
(
2L
,
"product 2"
,
25.9f
),
new
GoodsDto
(
3L
,
"product 3"
,
5.12f
),
new
GoodsDto
(
4L
,
"product 4"
,
55.29f
),
new
GoodsDto
(
5L
,
"product 5"
,
0.99f
)
).
toList
();
@Test
@DisplayName
(
"GET /api/goods/:id [200 OK]"
)
void
testGetGoods
()
throws
Exception
{
Long
id
=
1L
;
when
(
goodsService
.
getGoods
(
id
)).
thenReturn
(
goodsList
.
getFirst
());
mvc
.
perform
(
get
(
"/api/goods/{id}"
,
id
).
contentType
(
MediaType
.
APPLICATION_JSON
))
.
andExpect
(
status
().
isOk
())
.
andExpect
(
jsonPath
(
"$.id"
).
value
(
id
))
.
andExpect
(
jsonPath
(
"$.name"
).
value
(
goodsList
.
getFirst
().
getName
()));
}
@Test
@DisplayName
(
"GET /api/goods/:id [404 NotFound]"
)
void
testGetGoodNotFound
()
throws
Exception
{
Long
id
=
999L
;
when
(
goodsService
.
getGoods
(
id
)).
thenThrow
(
new
ResourceNotFoundException
());
mvc
.
perform
(
get
(
"/api/goods/{id}"
,
id
).
contentType
(
MediaType
.
APPLICATION_JSON
))
.
andExpect
(
status
().
isNotFound
());
}
@Test
@DisplayName
(
"GET /api/goods [200 OK]"
)
void
testGetAllGoodsPaged
()
throws
Exception
{
Page
<
GoodsDto
>
goodsPaged
=
new
PageImpl
<>(
goodsList
,
PageRequest
.
of
(
0
,
10
),
goodsList
.
size
());
when
(
goodsService
.
getPagedGoods
(
0
,
10
,
"id"
,
"ASC"
))
.
thenReturn
(
new
PagedModel
<>(
goodsPaged
));
mvc
.
perform
(
get
(
"/api/goods"
).
contentType
(
MediaType
.
APPLICATION_JSON
))
.
andExpect
(
status
().
isOk
())
.
andExpect
(
jsonPath
(
"$.content[0].id"
).
value
(
1
))
.
andExpect
(
jsonPath
(
"$.page.totalElements"
).
value
(
goodsList
.
size
()));
}
@Test
@DisplayName
(
"POST /api/goods [201 Created]"
)
void
testCreateGoods
()
throws
Exception
{
GoodsDto
goodsDto
=
new
GoodsDto
();
goodsDto
.
setName
(
"new product"
);
goodsDto
.
setPrice
(
199.99f
);
String
body
=
new
ObjectMapper
().
writeValueAsString
(
goodsDto
);
Long
nextId
=
goodsList
.
getLast
().
getId
()
+
1
;
goodsDto
.
setId
(
nextId
);
when
(
goodsService
.
createOrUpdateGoods
(
goodsMapper
.
toEntity
(
goodsDto
))).
thenReturn
(
goodsDto
);
mvc
.
perform
(
post
(
"/api/goods"
).
contentType
(
MediaType
.
APPLICATION_JSON
).
content
(
body
))
.
andExpect
(
status
().
isCreated
())
.
andExpect
(
jsonPath
(
"$.id"
).
isNumber
())
.
andExpect
(
jsonPath
(
"$.name"
).
value
(
goodsDto
.
getName
()))
.
andExpect
(
jsonPath
(
"$.price"
).
value
(
goodsDto
.
getPrice
()));
}
@Test
@DisplayName
(
"POST /api/goods [400 Bad Request]"
)
void
testCreateGoodsBadRequest
()
throws
Exception
{
JSONObject
bodyJson
=
new
JSONObject
(
"{'name': null, 'price': 0}"
);
mvc
.
perform
(
post
(
"/api/goods"
).
contentType
(
MediaType
.
APPLICATION_JSON
).
content
(
bodyJson
.
toString
()))
.
andExpect
(
status
().
isBadRequest
());
}
@Test
@DisplayName
(
"PUT /api/goods/:id [200 OK]"
)
void
testUpdateGoods
()
throws
Exception
{
Long
id
=
1L
;
GoodsDto
goods
=
new
GoodsDto
();
goods
.
setName
(
"product name"
);
goods
.
setPrice
(
0.99f
);
String
body
=
new
ObjectMapper
().
writeValueAsString
(
goods
);
goods
.
setId
(
id
);
when
(
goodsService
.
getGoods
(
id
)).
thenReturn
(
goodsList
.
getFirst
());
when
(
goodsService
.
createOrUpdateGoods
(
goodsMapper
.
toEntity
(
goods
))).
thenReturn
(
goods
);
mvc
.
perform
(
put
(
"/api/goods/{id}"
,
id
)
.
contentType
(
MediaType
.
APPLICATION_JSON
)
.
content
(
body
))
.
andExpect
(
status
().
isOk
())
.
andExpect
(
jsonPath
(
"$.name"
).
value
(
goods
.
getName
()));
}
@Test
@DisplayName
(
"DELETE /api/goods/:id [200 OK]"
)
void
testDeleteGoods
()
throws
Exception
{
Long
id
=
1L
;
doNothing
().
when
(
goodsService
).
deleteGoods
(
id
);
mvc
.
perform
(
delete
(
"/api/goods/{id}"
,
id
).
contentType
(
MediaType
.
APPLICATION_JSON
))
.
andExpect
(
status
().
isOk
());
}
@Test
@DisplayName
(
"DELETE /api/goods/:id [404 Not Found]"
)
void
testDeleteGoodsNotFound
()
throws
Exception
{
Long
id
=
999L
;
doThrow
(
new
ResourceNotFoundException
()).
doNothing
().
when
(
goodsService
).
deleteGoods
(
id
);
mvc
.
perform
(
delete
(
"/api/goods/{id}"
,
id
))
.
andExpect
(
status
().
isNotFound
());
}
}
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment