authorities = new HashSet<>();
37 | if (Objects.equals(username, "admin")) {
38 | authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
39 | }else {
40 | authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
41 | }
42 | logger.debug(String.format("User with name: %s and password: %s created.", user.getUsername(), user.getPassword()));
43 | return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), authorities);
44 | }else{
45 | throw new UsernameNotFoundException("User " + username + " not found!");
46 | }
47 | }
48 |
49 |
50 | }
51 |
--------------------------------------------------------------------------------
/src/main/java/com/syqu/shop/service/impl/UserServiceImpl.java:
--------------------------------------------------------------------------------
1 | package com.syqu.shop.service.impl;
2 |
3 | import com.syqu.shop.service.UserService;
4 | import com.syqu.shop.domain.User;
5 | import com.syqu.shop.repository.UserRepository;
6 | import org.slf4j.Logger;
7 | import org.slf4j.LoggerFactory;
8 | import org.springframework.beans.factory.annotation.Autowired;
9 | import org.springframework.security.authentication.AuthenticationManager;
10 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
11 | import org.springframework.security.core.context.SecurityContextHolder;
12 | import org.springframework.security.core.userdetails.UserDetails;
13 | import org.springframework.security.core.userdetails.UserDetailsService;
14 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
15 | import org.springframework.stereotype.Service;
16 |
17 | @Service
18 | public class UserServiceImpl implements UserService {
19 | private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
20 | private final UserRepository userRepository;
21 | private final UserDetailsService userDetailsService;
22 | private final BCryptPasswordEncoder bCryptPasswordEncoder;
23 | private final AuthenticationManager authenticationManager;
24 |
25 | @Autowired
26 | public UserServiceImpl(UserRepository userRepository, BCryptPasswordEncoder bCryptPasswordEncoder, UserDetailsService userDetailsService, AuthenticationManager authenticationManager) {
27 | this.userRepository = userRepository;
28 | this.bCryptPasswordEncoder = bCryptPasswordEncoder;
29 | this.userDetailsService = userDetailsService;
30 | this.authenticationManager = authenticationManager;
31 | }
32 |
33 | @Override
34 | public void save(User user) {
35 | user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
36 | userRepository.save(user);
37 | }
38 |
39 | @Override
40 | public void login(String username, String password) {
41 | UserDetails userDetails = userDetailsService.loadUserByUsername(username);
42 | UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(userDetails, password, userDetails.getAuthorities());
43 | authenticationManager.authenticate(token);
44 |
45 | if (token.isAuthenticated()) {
46 | SecurityContextHolder.getContext().setAuthentication(token);
47 | logger.debug(String.format("User %s logged in successfully!", username));
48 | }else{
49 | logger.error(String.format("Error with %s authentication!", username));
50 | }
51 | }
52 |
53 | @Override
54 | public User findByUsername(String username) {
55 | return userRepository.findByUsername(username);
56 | }
57 |
58 | @Override
59 | public User findByEmail(String email) {
60 | return userRepository.findByEmail(email);
61 | }
62 |
63 | @Override
64 | public User findById(long id) {
65 | return userRepository.findById(id);
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/src/main/java/com/syqu/shop/validator/ProductValidator.java:
--------------------------------------------------------------------------------
1 | package com.syqu.shop.validator;
2 |
3 | import com.syqu.shop.domain.Product;
4 | import org.springframework.stereotype.Component;
5 | import org.springframework.validation.Errors;
6 | import org.springframework.validation.ValidationUtils;
7 | import org.springframework.validation.Validator;
8 |
9 | @Component
10 | public class ProductValidator implements Validator {
11 |
12 | @Override
13 | public boolean supports(Class> aClass) {
14 | return Product.class.equals(aClass);
15 | }
16 |
17 | @Override
18 | public void validate(Object o, Errors errors) {
19 | Product product = (Product) o;
20 |
21 | ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name","error.not_empty");
22 | ValidationUtils.rejectIfEmptyOrWhitespace(errors, "description", "error.not_empty");
23 | ValidationUtils.rejectIfEmptyOrWhitespace(errors, "price", "error.not_empty");
24 |
25 | // Name must have from 2 characters to 32
26 | if (product.getName().length() <= 1) {
27 | errors.rejectValue("name", "product.error.name.less_2");
28 | }
29 | if (product.getName().length() > 32) {
30 | errors.rejectValue("name", "product.error.name.over_32");
31 | }
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/src/main/java/com/syqu/shop/validator/UserValidator.java:
--------------------------------------------------------------------------------
1 | package com.syqu.shop.validator;
2 |
3 | import com.syqu.shop.domain.User;
4 | import com.syqu.shop.service.UserService;
5 | import org.springframework.beans.factory.annotation.Autowired;
6 | import org.springframework.stereotype.Component;
7 | import org.springframework.validation.Errors;
8 | import org.springframework.validation.ValidationUtils;
9 | import org.springframework.validation.Validator;
10 |
11 | @Component
12 | public class UserValidator implements Validator {
13 | private final UserService userService;
14 |
15 | @Autowired
16 | public UserValidator(UserService userService) {
17 | this.userService = userService;
18 | }
19 |
20 | @Override
21 | public boolean supports(Class> aClass) {
22 | return User.class.equals(aClass);
23 | }
24 |
25 | @Override
26 | public void validate(Object o, Errors errors) {
27 | User user = (User) o;
28 |
29 | //Username and password can't me empty or contain whitespace
30 | ValidationUtils.rejectIfEmptyOrWhitespace(errors, "username", "error.not_empty");
31 | ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "error.not_empty");
32 |
33 | // Username must have from 4 characters to 32
34 | if (user.getUsername().length() < 4) {
35 | errors.rejectValue("username", "register.error.username.less_4");
36 | }
37 | if(user.getUsername().length() > 32){
38 | errors.rejectValue("username","register.error.username.over_32");
39 | }
40 | //Username can't be duplicated
41 | if (userService.findByUsername(user.getUsername()) != null) {
42 | errors.rejectValue("username", "register.error.duplicated.username");
43 | }
44 | //Email can't be duplicated
45 | if (userService.findByEmail(user.getEmail()) != null){
46 | errors.rejectValue("email", "register.error.duplicated.email");
47 | }
48 | //Password must have at least 8 characters and max 32
49 | if (user.getPassword().length() < 8) {
50 | errors.rejectValue("password", "register.error.password.less_8");
51 | }
52 | if (user.getPassword().length() > 32){
53 | errors.rejectValue("password", "register.error.password.over_32");
54 | }
55 | //Password must be the same as the confirmation password
56 | if (!user.getPasswordConfirm().equals(user.getPassword())) {
57 | errors.rejectValue("passwordConfirm", "register.error.diff_password");
58 | }
59 | //Age needs to be higher than 13
60 | if (user.getAge() <= 13){
61 | errors.rejectValue("age", "register.error.age_size");
62 | }
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/src/main/resources/application.properties:
--------------------------------------------------------------------------------
1 | #Port
2 | server.port=8080
3 |
4 | #Main
5 | spring.application.name=E-shop N3XT
6 |
7 | #Thymeleaf
8 | spring.thymeleaf.cache=false
9 |
10 | #JPA
11 | spring.jpa.hibernate.ddl-auto=create
12 | spring.jpa.show-sql=true
13 |
14 | # H2 DB
15 | spring.h2.console.enabled=true
16 | spring.datasource.hikari.driver-class-name=org.h2.Driver
17 | spring.datasource.hikari.jdbc-url=jdbc:h2:mem:testdb
18 | spring.datasource.hikari.username=sa
19 | spring.datasource.hikari.password=
20 |
21 | #Logging
22 | logging.level.org.springframework.jdbc=debug
23 |
24 | #Template Engine
25 | spring.mvc.view.prefix=classpath:/templates/
26 | spring.mvc.view.suffix=.html
27 |
--------------------------------------------------------------------------------
/src/main/resources/banner.txt:
--------------------------------------------------------------------------------
1 | _____ _ _ _ _____ __ __ _____
2 | | ___| | | | \ | ||____ |\ \ / /|_ _|
3 | | |__ ______ ___ | |__ ___ _ __ | \| | / / \ V / | |
4 | | __| |______|/ __|| '_ \ / _ \ | '_ \ | . ` | \ \ / \ | |
5 | | |___ \__ \| | | || (_) || |_) | | |\ |.___/ // /^\ \ | |
6 | \____/ |___/|_| |_| \___/ | .__/ \_| \_/\____/ \/ \/ \_/
7 | | |
8 | |_|
9 |
10 | :: Spring Boot Version :: ${spring-boot.version}
11 |
12 |
--------------------------------------------------------------------------------
/src/main/resources/i18n/messages.properties:
--------------------------------------------------------------------------------
1 | footer.copyright=\u00A92018 by Aleksander Lejawa - aleklejawa@gmail.com
2 | footer.language.en=English
3 | footer.language.pl=Polish
4 | footer.language.den=German
5 | user.log_in=Log In
6 | user.log_out=Log Out
7 | user.username=Username
8 | user.email=E-mail
9 | user.password=Password
10 | user.confirm_password=Confirm password
11 | user.firstname=First Name
12 | user.lastname=Last Name
13 | user.city=City
14 | user.gender=Gender
15 | user.gender.hidden=Hidden
16 | user.gender.male=Male
17 | user.gender.female=Female
18 | user.age=Age
19 | admin.create.product=Add new product
20 | product.name=Name
21 | product.category=Category
22 | product.desc=Description
23 | product.image_url=Image Url
24 | product.price=Price
25 | product.confirm=Confirm new product
26 | product.add=Add to cart
27 | register.title=Registration
28 | register.button=Register
29 | register.required=Fields with * are required!
30 | error.not_empty=This field can't be empty.
31 | register.error.diff_password=Passwords needs to be the same.
32 | register.error.duplicated.email=This E-mail is already in use.
33 | register.error.duplicated.username=This username is already in use.
34 | register.error.age_size=You need at least 13 years to register.
35 | register.error.password.less_8=Password must have at least 8 characters.
36 | register.error.password.over_32=Password can't have more than 32 characters.
37 | register.error.username.less_4=Username must have at least 4 characters.
38 | register.error.username.over_32=Username can't have more than 32 characters.
39 | header.app.title=E-shop N3XT
40 | header.logged=Logged as:
41 | header.search=Search
42 | login.sign_in=Please Sign In
43 | login.no_account=You don't have an account?
44 | login.alert.logged_out=You have been logged out.
45 | about.name=About me
46 | about.title=About me
47 | about.text=Hello my name is Aleksander and i am from Poland. That is all, thanks for visiting this page. :)
48 | home.title=Hello World!
49 | home.back=Back to home
50 | error.title=Error:
51 | error.no_access=Sorry, you can't access this page.
52 | error.no_page=Looks like this page doesn't exist.
53 | error.internal=Internal server error.
54 | error.unhandled=Unhandled error.
55 | product.error.name.less_2=Name must have at least 2 characters.
56 | product.error.name.over_32=Title can't have more than 32 characters.
57 | product.cancel=Cancel
58 | product.count=Total products:
59 | cart.remove=Remove
60 | cart.clear=Clear
61 | cart.title=Cart
62 | cart.total=Total price:
63 | cart.checkout=Checkout
64 | cart.empty=Looks like your cart is empty.
65 | user.title=User
--------------------------------------------------------------------------------
/src/main/resources/i18n/messages_pl.properties:
--------------------------------------------------------------------------------
1 | footer.copyright=\u00A92018 by Aleksander Lejawa - aleklejawa@gmail.com
2 | footer.language.en=Angielski
3 | footer.language.pl=Polski
4 | footer.language.den=Niemiecki
5 | user.log_in=Zaloguj si\u0119
6 | user.log_out=Wyloguj si\u0119
7 | user.username=Nazwa u\u017Cytkownika
8 | user.email=Adres E-Mail
9 | user.password=Has\u0142o
10 | user.confirm_password=Powt\u00F3rz has\u0142o
11 | user.firstname=Imi\u0119
12 | user.lastname=Nazwisko
13 | user.city=Miasto
14 | user.gender=P\u0142e\u0107
15 | user.gender.hidden=Ukryta
16 | user.gender.male=M\u0119\u017Cczyzna
17 | user.gender.female=Kobieta
18 | user.age=Wiek
19 | admin.create.product=Utw\u00F3rz nowy produkt
20 | product.name=Nazwa
21 | product.desc=Opis
22 | product.image_url=Link do zdj\u0119cia
23 | product.price=Cena
24 | register.title=Rejestracja
25 | register.button=Zarejestruj si\u0119
26 | register.required=Pola z * s\u0105 wymagane!
27 | error.not_empty=To pole nie mo\u017Ce by\u0107 puste.
28 | register.error.diff_password=Has\u0142a musz\u0105 by\u0107 takie same.
29 | register.error.duplicated.email=Ten adres E-mail jest ju\u017C zaj\u0119ty.
30 | register.error.duplicated.username=Ta nazwa u\u017Cytkownika jest ju\u017C zaj\u0119ta.
31 | register.error.age_size=Musisz mie\u0107 przynajmniej 13 lat by dokona\u0107 rejestracji.
32 | register.error.password.less_8=Has\u0142o musi mie\u0107 przynajmniej 8 znak\u00F3w.
33 | register.error.password.over_32=Has\u0142o nie mo\u017Ce mie\u0107 wi\u0119cej ni\u017C 32 znaki.
34 | register.error.username.less_4=Nazwa u\u017Cytkownika musi mie\u0107 przynajmniej 4 znaki.
35 | register.error.username.over_32=Nazwa u\u017Cytkownika nie mo\u017Ce mie wi\u0119cej ni\u017C 32 znaki.
36 | header.app.title=E-shop N3XT
37 | header.logged=Zalogowany jako:
38 | header.search=Szukaj
39 | login.sign_in=Prosze si\u0119 zalogowa\u0107
40 | login.no_account=Nie masz jeszcze konta?
41 | login.alert.logged_out=Zosta\u0142e\u015B pomy\u015Blnie wylogowany.
42 | about.name=O mnie
43 | about.title=O mnie
44 | about.text=Cze\u015B\u0107, nazywam si\u00EA Aleksander i pochodz\u0119 z Polski. To wszystko, dzi\u0119kuje za odwiedzenie mojej strony. :)
45 | home.title=Witaj \u015Bwiecie!
46 | home.back=Powr\u00F3t do strony g\u0142\u00F3wnej
47 | error.title=B\u0142\u0105d:
48 | error.no_access=Nie masz wymaganych uprawnie\u0144.
49 | error.no_page=Wygl\u0105da na to, \u017Ce podana strona nie istnieje.
50 | error.internal=B\u0142\u0105d serwera.
51 | error.unhandled=Nieobs\u0142ugiwany b\u0142\u0105d.
52 | product.add=Dodaj do koszyka
53 | product.error.name.over_32=Tytu\u0142 nie mo\u017Ce mie\u0107 wi\u0119cej ni\u017C 32 znaki.
54 | product.error.name.less_2=Nazwa musi mie\u0107 przynajmniej 8 znak\u00F3w.
55 | product.cancel=Anuluj
56 | product.count=\u0141\u0105czna liczba produkt\u00F3w:
57 | cart.remove=Usu\u0144
58 | cart.clear=Wyczy\u015B\u0107
59 | cart.title=Koszyk
60 | cart.total=\u0141\u0105czna cena:
61 | cart.checkout=Finalizuj
62 | cart.empty=Wygl\u0105da na to \u017Ce tw\u00F3j koszyk jest pusty.
63 | user.title=U\u017Cytkownik
--------------------------------------------------------------------------------
/src/main/resources/static/css/style.css:
--------------------------------------------------------------------------------
1 | html {
2 | height: 100%;
3 | }
4 |
5 | body {
6 | background: rgb(209, 209, 216);
7 | position: relative;
8 | margin: 0;
9 | padding-bottom: 6rem;
10 | min-height: 100%;
11 | }
12 |
13 | span {
14 | padding-left: 5px;
15 | padding-right: 5px;
16 | }
17 |
18 | footer {
19 | position: absolute;
20 | bottom: 0;
21 | line-height: 50px;
22 | }
23 |
24 | .container {
25 | padding-top: 15px;
26 | padding-bottom: 8px;
27 | }
28 |
29 | .btn {
30 | padding-left: 10px;
31 | }
32 |
33 | .alert {
34 | padding-top: 5px;
35 | }
36 |
37 | #header-username{
38 | color: ghostwhite;
39 | }
40 |
41 | nav {
42 | height: 60px;
43 | }
44 |
45 | .navbar-brand {
46 | font-size: 30px;
47 | padding-left: 10px;
48 | padding-right: 15px;
49 | transition: all 300ms;
50 | }
51 |
52 | .navbar-brand:hover, .info-slide:active {
53 | transform: scale(1.5);
54 | }
55 |
56 | .card-deck {
57 | padding-left: 20px;
58 | }
59 |
60 | .card {
61 | max-width: 17rem;
62 | }
63 |
64 | #cart {
65 | width: 44px;
66 | height: 44px;
67 | }
--------------------------------------------------------------------------------
/src/main/resources/static/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/syqu22/spring-boot-shop-sample/7ce26d711e9fcff80bad07b6bfa7ba6fd2aac532/src/main/resources/static/favicon.ico
--------------------------------------------------------------------------------
/src/main/resources/static/images/brand.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/syqu22/spring-boot-shop-sample/7ce26d711e9fcff80bad07b6bfa7ba6fd2aac532/src/main/resources/static/images/brand.png
--------------------------------------------------------------------------------
/src/main/resources/static/images/brand.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |
--------------------------------------------------------------------------------
/src/main/resources/static/images/cart.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/syqu22/spring-boot-shop-sample/7ce26d711e9fcff80bad07b6bfa7ba6fd2aac532/src/main/resources/static/images/cart.png
--------------------------------------------------------------------------------
/src/main/resources/static/images/example1.PNG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/syqu22/spring-boot-shop-sample/7ce26d711e9fcff80bad07b6bfa7ba6fd2aac532/src/main/resources/static/images/example1.PNG
--------------------------------------------------------------------------------
/src/main/resources/static/js/lang.js:
--------------------------------------------------------------------------------
1 | function changeLanguage(lang) {
2 | let currentUrl = window.location.toString();
3 | let cleanUrl = currentUrl.split("?")[0];
4 |
5 | window.history.replace({}, window.title, cleanUrl + "?lang=" + lang);
6 | }
7 |
8 | $("#select-lang").change(function(){
9 | changeLanguage($(this).val());
10 | });
--------------------------------------------------------------------------------
/src/main/resources/templates/about.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
--------------------------------------------------------------------------------
/src/main/resources/templates/cart.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
--------------------------------------------------------------------------------
/src/main/resources/templates/error/403.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
18 |
19 |
20 |
21 |
22 |
23 |
--------------------------------------------------------------------------------
/src/main/resources/templates/error/404.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
18 |
19 |
20 |
21 |
22 |
23 |
--------------------------------------------------------------------------------
/src/main/resources/templates/error/500.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
18 |
19 |
20 |
21 |
22 |
23 |
--------------------------------------------------------------------------------
/src/main/resources/templates/error/error.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
18 |
19 |
20 |
21 |
22 |
23 |
--------------------------------------------------------------------------------
/src/main/resources/templates/fragments/footer.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
--------------------------------------------------------------------------------
/src/main/resources/templates/fragments/header.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
45 |
46 |
47 |
48 |
49 |
--------------------------------------------------------------------------------
/src/main/resources/templates/home.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
19 |
20 |
23 |
24 |
25 |
26 |
29 |
32 |
33 |
![Card image cap]()
34 |
38 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
--------------------------------------------------------------------------------
/src/main/resources/templates/login.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
43 |
44 |
45 |
46 |
--------------------------------------------------------------------------------
/src/main/resources/templates/product.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
52 |
53 |
54 |
55 |
56 |
57 |
--------------------------------------------------------------------------------
/src/main/resources/templates/register.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
71 |
72 |
73 |
74 |
--------------------------------------------------------------------------------
/src/main/resources/templates/user.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/src/test/java/com/syqu/shop/ApplicationTests.java:
--------------------------------------------------------------------------------
1 | package com.syqu.shop;
2 |
3 | import org.junit.Test;
4 | import org.junit.runner.RunWith;
5 | import org.springframework.boot.test.context.SpringBootTest;
6 | import org.springframework.test.context.junit4.SpringRunner;
7 |
8 | @RunWith(SpringRunner.class)
9 | @SpringBootTest
10 | public class ApplicationTests {
11 |
12 | @Test
13 | public void contextLoads() {
14 | }
15 |
16 | }
17 |
--------------------------------------------------------------------------------
/src/test/java/com/syqu/shop/controller/CartControllerMvcTests.java:
--------------------------------------------------------------------------------
1 | package com.syqu.shop.controller;
2 |
3 | import com.syqu.shop.service.ShoppingCartService;
4 | import com.syqu.shop.service.ProductService;
5 | import org.junit.Before;
6 | import org.junit.Test;
7 | import org.junit.runner.RunWith;
8 | import org.springframework.boot.test.context.SpringBootTest;
9 | import org.springframework.boot.test.mock.mockito.MockBean;
10 | import org.springframework.test.context.junit4.SpringRunner;
11 | import org.springframework.test.web.servlet.MockMvc;
12 | import org.springframework.test.web.servlet.setup.MockMvcBuilders;
13 | import org.springframework.web.servlet.view.InternalResourceViewResolver;
14 |
15 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
16 | import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
17 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
18 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
19 |
20 | @SpringBootTest
21 | @RunWith(SpringRunner.class)
22 | public class CartControllerMvcTests {
23 | private MockMvc mockMvc;
24 |
25 | @MockBean
26 | ShoppingCartService shoppingCartService;
27 |
28 | @MockBean
29 | ProductService productService;
30 |
31 | @Before
32 | public void setUp() {
33 | InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
34 | viewResolver.setPrefix("/WEB-INF/jsp/view/");
35 | viewResolver.setSuffix(".jsp");
36 |
37 | mockMvc = MockMvcBuilders.standaloneSetup(new CartController(shoppingCartService, productService))
38 | .setViewResolvers(viewResolver)
39 | .build();
40 | }
41 |
42 | @Test
43 | public void cartControllerStatus() throws Exception{
44 | this.mockMvc.perform(get("/cart")).andExpect(status().isOk())
45 | .andExpect(view().name("cart")).andDo(print());
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/src/test/java/com/syqu/shop/controller/ControllersTests.java:
--------------------------------------------------------------------------------
1 | package com.syqu.shop.controller;
2 |
3 | import org.junit.Test;
4 | import org.junit.runner.RunWith;
5 | import org.springframework.beans.factory.annotation.Autowired;
6 | import org.springframework.boot.test.context.SpringBootTest;
7 | import org.springframework.test.context.junit4.SpringRunner;
8 |
9 | import static org.assertj.core.api.Assertions.assertThat;
10 |
11 | @SpringBootTest
12 | @RunWith(SpringRunner.class)
13 | public class ControllersTests {
14 |
15 | @Autowired
16 | HomeController homeController;
17 | @Autowired
18 | LoginController loginController;
19 | @Autowired
20 | RegisterController registerController;
21 | @Autowired
22 | UserController userController;
23 | @Autowired
24 | ProductController productController;
25 | @Autowired
26 | CartController cartController;
27 |
28 | @Test
29 | public void checkIfHomeControllerNotNull() {
30 | assertThat(homeController).isNotNull();
31 | }
32 |
33 | @Test
34 | public void checkIfUserControllerNotNull() {
35 | assertThat(userController).isNotNull();
36 | }
37 |
38 | @Test
39 | public void checkIfLoginControllerNotNull() {
40 | assertThat(loginController).isNotNull();
41 | }
42 |
43 | @Test
44 | public void checkIfRegisterControllerNotNull() {
45 | assertThat(registerController).isNotNull();
46 | }
47 |
48 | @Test
49 | public void checkIfProductControllerNotNull() {
50 | assertThat(productController).isNotNull();
51 | }
52 |
53 | @Test
54 | public void checkIfCartControllerNotNull() {
55 | assertThat(cartController).isNotNull();
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/src/test/java/com/syqu/shop/controller/HomeControllerMvcTests.java:
--------------------------------------------------------------------------------
1 | package com.syqu.shop.controller;
2 |
3 |
4 | import com.syqu.shop.service.ProductService;
5 | import org.junit.Before;
6 | import org.junit.Test;
7 | import org.junit.runner.RunWith;
8 | import org.springframework.boot.test.context.SpringBootTest;
9 | import org.springframework.boot.test.mock.mockito.MockBean;
10 | import org.springframework.test.context.junit4.SpringRunner;
11 | import org.springframework.test.web.servlet.MockMvc;
12 | import org.springframework.test.web.servlet.setup.MockMvcBuilders;
13 | import org.springframework.web.servlet.view.InternalResourceViewResolver;
14 |
15 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
16 | import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
17 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
18 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
19 |
20 | @SpringBootTest
21 | @RunWith(SpringRunner.class)
22 | public class HomeControllerMvcTests {
23 | private MockMvc mockMvc;
24 |
25 | @MockBean
26 | private ProductService productService;
27 |
28 | @Before
29 | public void setUp() {
30 | InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
31 | viewResolver.setPrefix("/WEB-INF/jsp/view/");
32 | viewResolver.setSuffix(".jsp");
33 |
34 | mockMvc = MockMvcBuilders.standaloneSetup(new HomeController(productService))
35 | .setViewResolvers(viewResolver)
36 | .build();
37 | }
38 |
39 | @Test
40 | public void homeControllerStatus() throws Exception{
41 | this.mockMvc.perform(get("/")).andExpect(status().isOk())
42 | .andExpect(view().name("home")).andDo(print());
43 | }
44 |
45 | @Test
46 | public void homeControllerStatus2() throws Exception{
47 | this.mockMvc.perform(get("/index")).andExpect(status().isOk())
48 | .andExpect(view().name("home")).andDo(print());
49 | }
50 | @Test
51 |
52 | public void homeControllerStatus3() throws Exception{
53 | this.mockMvc.perform(get("/home")).andExpect(status().isOk())
54 | .andExpect(view().name("home")).andDo(print());
55 | }
56 | @Test
57 |
58 | public void homeControllerStatus4() throws Exception{
59 | this.mockMvc.perform(get("/about")).andExpect(status().isOk())
60 | .andExpect(view().name("about")).andDo(print());
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/src/test/java/com/syqu/shop/controller/LoginControllerMvcTests.java:
--------------------------------------------------------------------------------
1 | package com.syqu.shop.controller;
2 |
3 | import org.junit.Before;
4 | import org.junit.Test;
5 | import org.junit.runner.RunWith;
6 | import org.springframework.boot.test.context.SpringBootTest;
7 | import org.springframework.test.context.junit4.SpringRunner;
8 | import org.springframework.test.web.servlet.MockMvc;
9 | import org.springframework.test.web.servlet.setup.MockMvcBuilders;
10 | import org.springframework.web.servlet.view.InternalResourceViewResolver;
11 |
12 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
13 | import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
14 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
15 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
16 |
17 | @SpringBootTest
18 | @RunWith(SpringRunner.class)
19 | public class LoginControllerMvcTests {
20 | private MockMvc mockMvc;
21 |
22 | @Before
23 | public void setUp() {
24 | InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
25 | viewResolver.setPrefix("/WEB-INF/jsp/view/");
26 | viewResolver.setSuffix(".jsp");
27 |
28 | mockMvc = MockMvcBuilders.standaloneSetup(new LoginController())
29 | .setViewResolvers(viewResolver)
30 | .build();
31 | }
32 |
33 | @Test
34 | public void loginControllerStatus() throws Exception{
35 | this.mockMvc.perform(get("/login")).andExpect(status().isOk())
36 | .andExpect(view().name("login")).andDo(print());
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/src/test/java/com/syqu/shop/creator/ProductCreator.java:
--------------------------------------------------------------------------------
1 | package com.syqu.shop.creator;
2 |
3 | import com.syqu.shop.domain.Product;
4 |
5 | import java.math.BigDecimal;
6 | import java.util.HashSet;
7 | import java.util.Set;
8 |
9 | public class ProductCreator {
10 | public static final String NAME = "Test";
11 | public static final String DESCRIPTION = "testDescriptionTestDescription";
12 | public static final BigDecimal PRICE = BigDecimal.valueOf(1000);
13 | public static final String IMAGE_URL = "https://avatars1.githubusercontent.com/u/30699233?s=400&u=cf0bc2b388b5c72364aaaedf26a8aab63f97ffcc&v=4";
14 |
15 | public static Product createTestProduct(){
16 | Product testProduct = new Product();
17 |
18 | testProduct.setName(NAME);
19 | testProduct.setDescription(DESCRIPTION);
20 | testProduct.setPrice(PRICE);
21 | testProduct.setImageUrl(IMAGE_URL);
22 |
23 | return testProduct;
24 | }
25 |
26 | public static Set createTestProducts(){
27 | Set testProducts = new HashSet<>();
28 |
29 | testProducts.add(createTestProduct());
30 | testProducts.add(createTestProduct());
31 | testProducts.add(createTestProduct());
32 |
33 | return testProducts;
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/test/java/com/syqu/shop/creator/UserCreator.java:
--------------------------------------------------------------------------------
1 | package com.syqu.shop.creator;
2 |
3 | import com.syqu.shop.domain.User;
4 |
5 | import java.math.BigDecimal;
6 |
7 | public class UserCreator {
8 | public static final String USERNAME = "Test";
9 | public static final String PASSWORD = "longpassword123";
10 | public static final String FIRST_NAME = "Test";
11 | public static final String LAST_NAME = "Test";
12 | public static final int AGE = 23;
13 | public static final String EMAIL = "randomemail@gmail.test";
14 | public static final String GENDER = "Male";
15 | public static final BigDecimal BALANCE = new BigDecimal(1000);
16 | public static final String CITY = "Warsaw";
17 |
18 | public static User createTestUser() {
19 | User testObject = new User();
20 |
21 | testObject.setUsername(USERNAME);
22 | testObject.setPassword(PASSWORD);
23 | testObject.setPasswordConfirm(PASSWORD);
24 | testObject.setFirstName(FIRST_NAME);
25 | testObject.setLastName(LAST_NAME);
26 | testObject.setAge(AGE);
27 | testObject.setEmail(EMAIL);
28 | testObject.setGender(GENDER);
29 | testObject.setBalance(BALANCE);
30 | testObject.setCity(CITY);
31 |
32 | return testObject;
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src/test/java/com/syqu/shop/model/ProductEntityTests.java:
--------------------------------------------------------------------------------
1 | package com.syqu.shop.model;
2 |
3 | import com.syqu.shop.creator.ProductCreator;
4 | import com.syqu.shop.domain.Product;
5 | import org.junit.Rule;
6 | import org.junit.Test;
7 | import org.junit.rules.ExpectedException;
8 | import org.junit.runner.RunWith;
9 | import org.springframework.beans.factory.annotation.Autowired;
10 | import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
11 | import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
12 | import org.springframework.boot.test.context.SpringBootTest;
13 | import org.springframework.test.context.junit4.SpringRunner;
14 |
15 | import javax.persistence.PersistenceException;
16 | import javax.validation.ConstraintViolationException;
17 |
18 | @RunWith(SpringRunner.class)
19 | @SpringBootTest
20 | @DataJpaTest
21 | public class ProductEntityTests {
22 | @Rule
23 | public ExpectedException thrown = ExpectedException.none();
24 |
25 | @Autowired
26 | private TestEntityManager entityManager;
27 |
28 | @Test
29 | public void createProductWhenNameIsNullShouldThrowException() {
30 | this.thrown.expect(ConstraintViolationException.class);
31 | this.thrown.expectMessage("must not be null");
32 |
33 | Product testObject = ProductCreator.createTestProduct();
34 | testObject.setName(null);
35 |
36 | entityManager.persistAndFlush(testObject);
37 | }
38 |
39 | @Test
40 | public void createProductWhenNameIsEmptyShouldThrowException() {
41 | this.thrown.expect(ConstraintViolationException.class);
42 | this.thrown.expectMessage("must not be empty");
43 |
44 | Product testObject = ProductCreator.createTestProduct();
45 | testObject.setName("");
46 |
47 | entityManager.persistAndFlush(testObject);
48 | }
49 |
50 | @Test
51 | public void createProductWhenDescriptionIsNullShouldThrowException() {
52 | this.thrown.expect(ConstraintViolationException.class);
53 | this.thrown.expectMessage("must not be null");
54 |
55 | Product testObject = ProductCreator.createTestProduct();
56 | testObject.setDescription(null);
57 |
58 | entityManager.persistAndFlush(testObject);
59 | }
60 |
61 | @Test
62 | public void createProductWhenDescriptionIsEmptyShouldThrowException() {
63 | this.thrown.expect(ConstraintViolationException.class);
64 | this.thrown.expectMessage("must not be empty");
65 |
66 | Product testObject = ProductCreator.createTestProduct();
67 | testObject.setDescription("");
68 |
69 | entityManager.persistAndFlush(testObject);
70 | }
71 |
72 | @Test
73 | public void createProductWhenDescriptionIsToLongShouldThrowException() {
74 | this.thrown.expect(PersistenceException.class);
75 | this.thrown.expectMessage("org.hibernate.exception.DataException: could not execute statement");
76 |
77 | StringBuilder stringBuilder = new StringBuilder();
78 | for (int i=0;i<101;i++){
79 | stringBuilder.append("testtest");
80 | }
81 | Product testObject = ProductCreator.createTestProduct();
82 | testObject.setDescription(stringBuilder.toString());
83 |
84 | entityManager.persistAndFlush(testObject);
85 | }
86 |
87 | @Test
88 | public void createProductWhenImageUrlIsNotValidUrlShouldThrowException() {
89 | this.thrown.expect(ConstraintViolationException.class);
90 | this.thrown.expectMessage("org.hibernate.validator.constraints.URL.message");
91 |
92 | Product testObject = ProductCreator.createTestProduct();
93 | testObject.setImageUrl("htt://test");
94 |
95 | entityManager.persistAndFlush(testObject);
96 | }
97 |
98 | @Test
99 | public void createProductWhenPriceIsNullThrowException() {
100 | this.thrown.expect(ConstraintViolationException.class);
101 | this.thrown.expectMessage("must not be null");
102 |
103 | Product testObject = ProductCreator.createTestProduct();
104 | testObject.setPrice(null);
105 |
106 | entityManager.persistAndFlush(testObject);
107 | }
108 | }
109 |
--------------------------------------------------------------------------------
/src/test/java/com/syqu/shop/model/UserEntityTests.java:
--------------------------------------------------------------------------------
1 | package com.syqu.shop.model;
2 |
3 | import com.syqu.shop.creator.UserCreator;
4 | import com.syqu.shop.domain.User;
5 | import org.junit.Rule;
6 | import org.junit.Test;
7 | import org.junit.rules.ExpectedException;
8 | import org.junit.runner.RunWith;
9 | import org.springframework.beans.factory.annotation.Autowired;
10 | import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
11 | import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
12 | import org.springframework.boot.test.context.SpringBootTest;
13 | import org.springframework.test.context.junit4.SpringRunner;
14 |
15 | import javax.validation.ConstraintViolationException;
16 |
17 | @RunWith(SpringRunner.class)
18 | @SpringBootTest
19 | @DataJpaTest
20 | public class UserEntityTests {
21 | @Rule
22 | public ExpectedException thrown = ExpectedException.none();
23 |
24 | @Autowired
25 | private TestEntityManager entityManager;
26 |
27 | @Test
28 | public void createUserWhenUsernameIsNullShouldThrowException() {
29 | this.thrown.expect(ConstraintViolationException.class);
30 | this.thrown.expectMessage("must not be null");
31 |
32 | User testObject = UserCreator.createTestUser();
33 | testObject.setUsername(null);
34 |
35 | entityManager.persistAndFlush(testObject);
36 | }
37 |
38 | @Test
39 | public void createUserWhenUsernameIsEmptyShouldThrowException() {
40 | this.thrown.expect(ConstraintViolationException.class);
41 | this.thrown.expectMessage("must not be empty");
42 |
43 | User testObject = UserCreator.createTestUser();
44 | testObject.setUsername("");
45 |
46 | entityManager.persistAndFlush(testObject);
47 | }
48 |
49 | @Test
50 | public void createUserWhenEmailIsEmptyShouldThrowException() {
51 | this.thrown.expect(ConstraintViolationException.class);
52 | this.thrown.expectMessage("must not be empty");
53 |
54 | User testObject = UserCreator.createTestUser();
55 | testObject.setEmail("");
56 |
57 | entityManager.persistAndFlush(testObject);
58 | }
59 |
60 | @Test
61 | public void createUserWhenEmailHaveInvalidFormatShouldThrowException() {
62 | this.thrown.expect(ConstraintViolationException.class);
63 | this.thrown.expectMessage("must be a well-formed email address");
64 |
65 | User testObject = UserCreator.createTestUser();
66 | testObject.setEmail("syqu.pl");
67 |
68 | entityManager.persistAndFlush(testObject);
69 | }
70 |
71 | @Test
72 | public void createUserWhenEmailIsNullShouldThrowException() {
73 | this.thrown.expect(ConstraintViolationException.class);
74 | this.thrown.expectMessage("must not be null");
75 |
76 | User testObject = UserCreator.createTestUser();
77 | testObject.setEmail(null);
78 |
79 | entityManager.persistAndFlush(testObject);
80 | }
81 |
82 | @Test
83 | public void createUserWhenPasswordIsNullShouldThrowException() {
84 | this.thrown.expect(ConstraintViolationException.class);
85 | this.thrown.expectMessage("must not be null");
86 |
87 | User testObject = UserCreator.createTestUser();
88 | testObject.setPassword(null);
89 |
90 | entityManager.persistAndFlush(testObject);
91 | }
92 |
93 | @Test
94 | public void createUserWhenPasswordIsEmptyShouldThrowException() {
95 | this.thrown.expect(ConstraintViolationException.class);
96 | this.thrown.expectMessage("must not be empty");
97 |
98 | User testObject = UserCreator.createTestUser();
99 | testObject.setPassword("");
100 |
101 | entityManager.persistAndFlush(testObject);
102 | }
103 |
104 | @Test
105 | public void createUserWhenPasswordConfirmIsNullShouldThrowException() {
106 | this.thrown.expect(ConstraintViolationException.class);
107 | this.thrown.expectMessage("must not be null");
108 |
109 | User testObject = UserCreator.createTestUser();
110 | testObject.setPasswordConfirm(null);
111 |
112 | entityManager.persistAndFlush(testObject);
113 | }
114 |
115 | @Test
116 | public void createUserWhenPasswordConfirmIsEmptyShouldThrowException() {
117 | this.thrown.expect(ConstraintViolationException.class);
118 | this.thrown.expectMessage("must not be empty");
119 |
120 | User testObject = UserCreator.createTestUser();
121 | testObject.setPasswordConfirm("");
122 |
123 | entityManager.persistAndFlush(testObject);
124 | }
125 |
126 | @Test
127 | public void createUserWhenGenderIsNullShouldThrowException() {
128 | this.thrown.expect(ConstraintViolationException.class);
129 | this.thrown.expectMessage("must not be null");
130 |
131 | User testObject = UserCreator.createTestUser();
132 | testObject.setGender(null);
133 |
134 | entityManager.persistAndFlush(testObject);
135 | }
136 |
137 | @Test
138 | public void createUserWhenGenderIsEmptyShouldThrowException() {
139 | this.thrown.expect(ConstraintViolationException.class);
140 | this.thrown.expectMessage("must not be empty");
141 |
142 | User testObject = UserCreator.createTestUser();
143 | testObject.setGender("");
144 |
145 | entityManager.persistAndFlush(testObject);
146 | }
147 | }
148 |
--------------------------------------------------------------------------------
/src/test/java/com/syqu/shop/repository/ProductRepositoryTests.java:
--------------------------------------------------------------------------------
1 | package com.syqu.shop.repository;
2 |
3 | import com.syqu.shop.creator.ProductCreator;
4 | import com.syqu.shop.domain.Product;
5 | import org.junit.Test;
6 | import org.junit.runner.RunWith;
7 | import org.springframework.beans.factory.annotation.Autowired;
8 | import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
9 | import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
10 | import org.springframework.boot.test.context.SpringBootTest;
11 | import org.springframework.test.context.junit4.SpringRunner;
12 |
13 | import java.util.List;
14 | import java.util.Random;
15 |
16 | import static org.assertj.core.api.Assertions.assertThat;
17 |
18 | @DataJpaTest
19 | @SpringBootTest
20 | @RunWith(SpringRunner.class)
21 | public class ProductRepositoryTests {
22 |
23 | @Autowired
24 | private TestEntityManager entityManager;
25 |
26 | @Autowired
27 | private ProductRepository productRepository;
28 |
29 | @Test
30 | public void checkIfProductRepositoryIsNotNull(){
31 | assertThat(productRepository).isNotNull();
32 | }
33 |
34 | @Test
35 | public void checkIfParamsAreTheSame(){
36 | Product testObject = ProductCreator.createTestProduct();
37 | entityManager.persistAndFlush(testObject);
38 |
39 | Product found = productRepository.findByName(testObject.getName());
40 |
41 | assertThat(found.getId()).isEqualTo(testObject.getId());
42 | assertThat(found.getName()).isEqualTo(testObject.getName());
43 | assertThat(found.getDescription()).isEqualTo(testObject.getDescription());
44 | assertThat(found.getPrice()).isEqualTo(testObject.getPrice());
45 | assertThat(found.getImageUrl()).isEqualTo(testObject.getImageUrl());
46 | }
47 |
48 | @Test
49 | public void whenFindByNameThenReturnProduct() {
50 | Product testObject = ProductCreator.createTestProduct();
51 | entityManager.persistAndFlush(testObject);
52 |
53 | Product found = productRepository.findByName(testObject.getName());
54 | assertThat(found.getName()).isEqualTo(testObject.getName());
55 | }
56 |
57 | @Test
58 | public void whenFindByIdThenReturnProduct(){
59 | Product testObject = ProductCreator.createTestProduct();
60 | entityManager.persistAndFlush(testObject);
61 |
62 | Product found = productRepository.findById(testObject.getId());
63 | assertThat(found.getId()).isEqualTo(testObject.getId());
64 | }
65 |
66 | @Test
67 | public void whenFindAllByOrderByIdAscThenReturnAllProducts(){
68 | Product testObject1 = ProductCreator.createTestProduct();
69 | Product testObject2 = ProductCreator.createTestProduct();
70 | Product testObject3 = ProductCreator.createTestProduct();
71 | entityManager.persistAndFlush(testObject1);
72 | entityManager.persistAndFlush(testObject2);
73 | entityManager.persistAndFlush(testObject3);
74 |
75 | List found = productRepository.findAllByOrderByIdAsc();
76 | assertThat(found.size()).isEqualTo(3);
77 | assertThat(found.get(0).getId()).isEqualTo(testObject1.getId());
78 | assertThat(found.get(1).getId()).isEqualTo(testObject2.getId());
79 | assertThat(found.get(2).getId()).isEqualTo(testObject3.getId());
80 | }
81 |
82 | @Test
83 | public void whenFindByIdAndNoProductReturnNull(){
84 | assertThat(productRepository.findById(new Random().nextLong())).isNull();
85 | }
86 |
87 | @Test
88 | public void whenFindByNameAndNoProductReturnNull(){
89 | assertThat(productRepository.findByName("random string")).isNull();
90 | }
91 |
92 | @Test
93 | public void whenFindAllByOrderByIdAscAndNoProductsReturnNull(){
94 | assertThat(productRepository.findAllByOrderByIdAsc()).isNullOrEmpty();
95 | }
96 | }
97 |
--------------------------------------------------------------------------------
/src/test/java/com/syqu/shop/repository/UserRepositoryTests.java:
--------------------------------------------------------------------------------
1 | package com.syqu.shop.repository;
2 |
3 | import com.syqu.shop.creator.UserCreator;
4 | import com.syqu.shop.domain.User;
5 | import org.junit.Test;
6 | import org.junit.runner.RunWith;
7 | import org.springframework.beans.factory.annotation.Autowired;
8 | import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
9 | import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
10 | import org.springframework.boot.test.context.SpringBootTest;
11 | import org.springframework.test.context.junit4.SpringRunner;
12 |
13 | import java.util.Random;
14 |
15 | import static org.assertj.core.api.Assertions.assertThat;
16 |
17 | @DataJpaTest
18 | @SpringBootTest
19 | @RunWith(SpringRunner.class)
20 | public class UserRepositoryTests {
21 |
22 | @Autowired
23 | private TestEntityManager entityManager;
24 |
25 | @Autowired
26 | private UserRepository userRepository;
27 |
28 | @Test
29 | public void checkIfUserRepositoryIsNotNull(){
30 | assertThat(userRepository).isNotNull();
31 | }
32 |
33 | @Test
34 | public void checkIfParamsAreTheSame(){
35 | User testObject = UserCreator.createTestUser();
36 | entityManager.persistAndFlush(testObject);
37 |
38 | User found = userRepository.findByUsername(testObject.getUsername());
39 |
40 | assertThat(found.getId()).isEqualTo(testObject.getId());
41 | assertThat(found.getUsername()).isEqualTo(testObject.getUsername());
42 | assertThat(found.getPassword()).isEqualTo(testObject.getPassword());
43 | assertThat(found.getPasswordConfirm()).isEqualTo(found.getPassword());
44 | assertThat(found.getPasswordConfirm()).isEqualTo(testObject.getPasswordConfirm());
45 | assertThat(found.getFirstName()).isEqualTo(testObject.getFirstName());
46 | assertThat(found.getLastName()).isEqualTo(testObject.getLastName());
47 | assertThat(found.getEmail()).isEqualTo(testObject.getEmail());
48 | assertThat(found.getAge()).isEqualTo(testObject.getAge());
49 | assertThat(found.getBalance()).isEqualTo(testObject.getBalance());
50 | assertThat(found.getCity()).isEqualTo(testObject.getCity());
51 | assertThat(found.getGender()).isEqualTo(testObject.getGender());
52 | }
53 |
54 | @Test
55 | public void whenFindByEmailThenReturnUser(){
56 | User testObject = UserCreator.createTestUser();
57 |
58 | entityManager.persistAndFlush(testObject);
59 |
60 | User found = userRepository.findByEmail(testObject.getEmail());
61 | assertThat(found.getEmail()).isEqualTo(testObject.getEmail());
62 | }
63 |
64 | @Test
65 | public void whenFindByIdThenReturnUser(){
66 | User testObject = UserCreator.createTestUser();
67 |
68 | entityManager.persistAndFlush(testObject);
69 |
70 | User found = userRepository.findById(testObject.getId());
71 | assertThat(found.getId()).isEqualTo(testObject.getId());
72 | }
73 |
74 | @Test
75 | public void whenFindByIdAndNoUserThenReturnNull() {
76 | assertThat(userRepository.findById(new Random().nextLong())).isNull();
77 | }
78 |
79 | @Test
80 | public void whenFindByUsernameAndNoUserThenReturnNull() {
81 | assertThat(userRepository.findByUsername("xxminecraftplayerxx")).isNull();
82 | }
83 |
84 | @Test
85 | public void whenFindByEmailAndNoUserThenReturnNull() {
86 | assertThat(userRepository.findByEmail("whatis@going.on")).isNull();
87 | }
88 | }
89 |
--------------------------------------------------------------------------------
/src/test/java/com/syqu/shop/service/ProductServiceTests.java:
--------------------------------------------------------------------------------
1 | package com.syqu.shop.service;
2 |
3 | import com.syqu.shop.creator.ProductCreator;
4 | import com.syqu.shop.domain.Product;
5 | import org.junit.Test;
6 | import org.junit.runner.RunWith;
7 | import org.springframework.boot.test.context.SpringBootTest;
8 | import org.springframework.boot.test.mock.mockito.MockBean;
9 | import org.springframework.test.context.junit4.SpringRunner;
10 |
11 | import java.math.BigDecimal;
12 | import java.util.ArrayList;
13 | import java.util.List;
14 |
15 | import static org.assertj.core.api.Assertions.assertThat;
16 | import static org.mockito.Mockito.when;
17 | import static org.mockito.MockitoAnnotations.initMocks;
18 |
19 | @RunWith(SpringRunner.class)
20 | @SpringBootTest
21 | public class ProductServiceTests {
22 |
23 | @MockBean
24 | private ProductService productService;
25 |
26 | @Test
27 | public void checkIfProductServiceIsNotNull(){
28 | initMocks(this);
29 |
30 | assertThat(productService).isNotNull();
31 | }
32 | @Test
33 | public void saveProductTests(){
34 | Product product = ProductCreator.createTestProduct();
35 | productService.save(product);
36 | when(productService.findById(product.getId())).thenReturn(product);
37 | Product found = productService.findById(product.getId());
38 |
39 | assertThat(found).isNotNull();
40 | assertThat(found.getName()).isEqualTo(product.getName());
41 | assertThat(found.getDescription()).isEqualTo(product.getDescription());
42 | assertThat(found.getPrice()).isEqualTo(product.getPrice());
43 | assertThat(found.getImageUrl()).isEqualTo(product.getImageUrl());
44 | }
45 |
46 | @Test
47 | public void editProductsTests(){
48 | Product product = ProductCreator.createTestProduct();
49 | Product newProduct = ProductCreator.createTestProduct();
50 | newProduct.setName("Hello");
51 | newProduct.setPrice(BigDecimal.valueOf(50));
52 | newProduct.setDescription("Hello Description :)");
53 |
54 | productService.save(product);
55 | productService.edit(product.getId(), newProduct);
56 |
57 | when(productService.findById(product.getId())).thenReturn(newProduct);
58 | Product found = productService.findById(newProduct.getId());
59 |
60 | assertThat(found).isNotNull();
61 | assertThat(found.getPrice()).isEqualTo(BigDecimal.valueOf(50));
62 | assertThat(found.getName()).isEqualTo("Hello");
63 | assertThat(found.getDescription()).isEqualTo("Hello Description :)");
64 | }
65 |
66 | @Test
67 | public void deleteProductsTests(){
68 | Product product = ProductCreator.createTestProduct();
69 | productService.save(product);
70 | productService.delete(product.getId());
71 |
72 | Product found = productService.findById(product.getId());
73 |
74 | assertThat(found).isNull();
75 | }
76 |
77 | @Test
78 | public void whenFindByIdThenReturnProduct(){
79 | when(productService.findById(100L)).thenReturn(ProductCreator.createTestProduct());
80 | Product found = productService.findById(100L);
81 |
82 | assertThat(found).isNotNull();
83 | assertThat(found.getName()).isEqualTo(ProductCreator.NAME);
84 | assertThat(found.getDescription()).isEqualTo(ProductCreator.DESCRIPTION);
85 | assertThat(found.getPrice()).isEqualTo(ProductCreator.PRICE);
86 | assertThat(found.getImageUrl()).isEqualTo(ProductCreator.IMAGE_URL);
87 | }
88 |
89 | @Test
90 | public void whenFindAllByOrderByIdAscThenReturnAllProducts(){
91 | ArrayList products = new ArrayList<>(ProductCreator.createTestProducts());
92 | when(productService.findAllByOrderByIdAsc()).thenReturn(products);
93 | List found = productService.findAllByOrderByIdAsc();
94 |
95 | assertThat(found).isNotNull();
96 | for (Product product : found){
97 | assertThat(product.getName()).isEqualTo(ProductCreator.NAME);
98 | assertThat(product.getDescription()).isEqualTo(ProductCreator.DESCRIPTION);
99 | assertThat(product.getPrice()).isEqualTo(ProductCreator.PRICE);
100 | assertThat(product.getImageUrl()).isEqualTo(ProductCreator.IMAGE_URL);
101 | }
102 | }
103 |
104 | @Test
105 | public void whenCountThenReturnProductsCount(){
106 | when(productService.count()).thenReturn(3L);
107 | long count = productService.count();
108 |
109 | assertThat(count).isNotNegative();
110 | assertThat(count).isEqualTo(3L);
111 |
112 | }
113 |
114 | @Test
115 | public void whenFindByIdAndNoProductThenReturnNull(){
116 | Product found = productService.findById(50L);
117 |
118 | assertThat(found).isNull();
119 | }
120 | }
121 |
--------------------------------------------------------------------------------
/src/test/java/com/syqu/shop/service/ShoppingCartServiceTests.java:
--------------------------------------------------------------------------------
1 | package com.syqu.shop.service;
2 |
3 | import com.syqu.shop.creator.ProductCreator;
4 | import com.syqu.shop.domain.Product;
5 | import org.junit.Test;
6 | import org.junit.runner.RunWith;
7 | import org.springframework.boot.test.context.SpringBootTest;
8 | import org.springframework.boot.test.mock.mockito.MockBean;
9 | import org.springframework.test.context.junit4.SpringRunner;
10 |
11 | import java.util.LinkedHashMap;
12 | import java.util.Map;
13 |
14 | import static org.assertj.core.api.Assertions.assertThat;
15 | import static org.mockito.Mockito.when;
16 | import static org.mockito.MockitoAnnotations.initMocks;
17 |
18 | @RunWith(SpringRunner.class)
19 | @SpringBootTest
20 | public class ShoppingCartServiceTests {
21 |
22 | @MockBean
23 | private ShoppingCartService shoppingCartService;
24 |
25 | @Test
26 | public void checkIfShoppingCartServiceIsNotNull() {
27 | initMocks(this);
28 |
29 | assertThat(shoppingCartService).isNotNull();
30 | }
31 |
32 | @Test
33 | public void addProductToCartTests(){
34 | Map cart = new LinkedHashMap<>();
35 | Product product = ProductCreator.createTestProduct();
36 |
37 | when(shoppingCartService.productsInCart()).thenReturn(cart);
38 |
39 | cart.put(product, 1);
40 |
41 | assertThat(shoppingCartService.productsInCart()).containsKey(product);
42 | }
43 |
44 | @Test
45 | public void addTwoTheSameProductsToCartTests(){
46 | Map cart = new LinkedHashMap<>();
47 | Product product = ProductCreator.createTestProduct();
48 | Product product2 = ProductCreator.createTestProduct();
49 |
50 | when(shoppingCartService.productsInCart()).thenReturn(cart);
51 |
52 | product.setName("Not Bad Trainers");
53 | product2.setName("Nice Shoes");
54 |
55 | cart.put(product, 1);
56 | cart.put(product2, 1);
57 |
58 | assertThat(shoppingCartService.productsInCart()).containsKey(product);
59 | assertThat(shoppingCartService.productsInCart()).containsKey(product2);
60 | }
61 |
62 | @Test
63 | public void removeProductFromCartTests(){
64 | Map cart = new LinkedHashMap<>();
65 | Product product = ProductCreator.createTestProduct();
66 |
67 | when(shoppingCartService.productsInCart()).thenReturn(cart);
68 |
69 | cart.put(product, 1);
70 | assertThat(shoppingCartService.productsInCart()).containsKey(product);
71 |
72 | cart.remove(product);
73 | assertThat(shoppingCartService.productsInCart()).doesNotContainKey(product);
74 | }
75 | }
76 |
--------------------------------------------------------------------------------
/src/test/java/com/syqu/shop/service/UserServiceTests.java:
--------------------------------------------------------------------------------
1 | package com.syqu.shop.service;
2 |
3 | import com.syqu.shop.creator.UserCreator;
4 | import com.syqu.shop.domain.User;
5 | import org.junit.Test;
6 | import org.junit.runner.RunWith;
7 | import org.springframework.boot.test.context.SpringBootTest;
8 | import org.springframework.boot.test.mock.mockito.MockBean;
9 | import org.springframework.test.context.junit4.SpringRunner;
10 |
11 | import static org.assertj.core.api.Assertions.assertThat;
12 | import static org.mockito.Mockito.when;
13 | import static org.mockito.MockitoAnnotations.initMocks;
14 |
15 | @RunWith(SpringRunner.class)
16 | @SpringBootTest
17 | public class UserServiceTests {
18 |
19 | @MockBean
20 | private UserService userService;
21 |
22 | @Test
23 | public void checkIfUserServiceIsNotNull(){
24 | initMocks(this);
25 |
26 | assertThat(userService).isNotNull();
27 | }
28 |
29 | @Test
30 | public void saveUserTests(){
31 | User user = UserCreator.createTestUser();
32 | userService.save(user);
33 | when(userService.findById(user.getId())).thenReturn(user);
34 | User found = userService.findById(user.getId());
35 |
36 | assertThat(found).isNotNull();
37 | assertThat(found.getUsername()).isEqualTo(user.getUsername());
38 | assertThat(found.getEmail()).isEqualTo(user.getEmail());
39 | assertThat(found.getAge()).isEqualTo(user.getAge());
40 | assertThat(found.getGender()).isEqualTo(user.getGender());
41 | }
42 |
43 | @Test
44 | public void whenFindByIdThenReturnUser() {
45 | when(userService.findById(100L)).thenReturn(UserCreator.createTestUser());
46 | User found = userService.findById(100L);
47 |
48 | assertThat(found).isNotNull();
49 | assertThat(found.getUsername()).isEqualTo(UserCreator.USERNAME);
50 | assertThat(found.getEmail()).isEqualTo(UserCreator.EMAIL);
51 | assertThat(found.getAge()).isEqualTo(UserCreator.AGE);
52 | assertThat(found.getGender()).isEqualTo(UserCreator.GENDER);
53 | }
54 |
55 | @Test
56 | public void whenFindByUsernameThenReturnUser() {
57 | initMocks(this);
58 |
59 | when(userService.findByUsername(UserCreator.USERNAME)).thenReturn(UserCreator.createTestUser());
60 | User found = userService.findByUsername(UserCreator.USERNAME);
61 |
62 | assertThat(found.getUsername()).isEqualTo(UserCreator.USERNAME);
63 | assertThat(found.getEmail()).isEqualTo(UserCreator.EMAIL);
64 | assertThat(found.getAge()).isEqualTo(UserCreator.AGE);
65 | assertThat(found.getGender()).isEqualTo(UserCreator.GENDER);
66 | }
67 |
68 | @Test
69 | public void whenFindByEmailThenReturnUser() {
70 | initMocks(this);
71 |
72 | when(userService.findByEmail(UserCreator.EMAIL)).thenReturn(UserCreator.createTestUser());
73 | User found = userService.findByEmail(UserCreator.EMAIL);
74 |
75 | assertThat(found).isNotNull();
76 | assertThat(found.getUsername()).isEqualTo(UserCreator.USERNAME);
77 | assertThat(found.getEmail()).isEqualTo(UserCreator.EMAIL);
78 | assertThat(found.getAge()).isEqualTo(UserCreator.AGE);
79 | assertThat(found.getGender()).isEqualTo(UserCreator.GENDER);
80 | }
81 |
82 | @Test
83 | public void whenFindByIdAndNoUserThenReturnNull(){
84 | User found = userService.findById(25L);
85 |
86 | assertThat(found).isNull();
87 | }
88 |
89 | @Test
90 | public void whenFindByUsernameAndNoUserThenReturnNull(){
91 | User found = userService.findByUsername("Tests");
92 |
93 | assertThat(found).isNull();
94 | }
95 |
96 | @Test
97 | public void whenFindByEmailAndNoUserThenReturnNull(){
98 | User found = userService.findByEmail("example@donut.org");
99 |
100 | assertThat(found).isNull();
101 | }
102 | }
103 |
--------------------------------------------------------------------------------