test 정리

dev
Lim Jonguk 3 years ago
parent b2c0a1574c
commit 39df7f7dd6

@ -74,6 +74,8 @@ dependencies {
implementation 'org.springframework.boot:spring-boot-starter-security' implementation 'org.springframework.boot:spring-boot-starter-security'
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-jdbc' implementation 'org.springframework.boot:spring-boot-starter-jdbc'
// jta module
//implementation('org.springframework.boot:spring-boot-starter-jta-atomikos')
// yaml lib // yaml lib
implementation 'net.rakugakibox.util:yaml-resource-bundle:1.2' implementation 'net.rakugakibox.util:yaml-resource-bundle:1.2'
@ -231,6 +233,8 @@ dependencies {
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.2' //'junit:junit:4.13.2' testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.2' //'junit:junit:4.13.2'
testImplementation 'org.junit.jupiter:junit-jupiter-params:5.8.2' //'junit:junit:4.13.2' testImplementation 'org.junit.jupiter:junit-jupiter-params:5.8.2' //'junit:junit:4.13.2'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.2' //'junit:junit:4.13.2' testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.2' //'junit:junit:4.13.2'
testRuntimeOnly 'org.hamcrest:hamcrest-library:2.2'
testRuntimeOnly 'com.jayway.jsonpath:json-path:2.5.0'
implementation 'org.assertj:assertj-core:3.21.0' implementation 'org.assertj:assertj-core:3.21.0'
testCompileOnly 'org.projectlombok:lombok' testCompileOnly 'org.projectlombok:lombok'

@ -4,6 +4,7 @@ import com.xit.core.constant.XitConstants;
import com.xit.core.oauth2.oauth.AuthInterceptor; import com.xit.core.oauth2.oauth.AuthInterceptor;
import com.xit.core.support.RestTemplateLoggingRequestInterceptor; import com.xit.core.support.RestTemplateLoggingRequestInterceptor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.MessageSource; import org.springframework.context.MessageSource;
@ -266,40 +267,40 @@ public class WebCommonConfig extends AsyncConfigurerSupport implements WebMvcCon
return executor; return executor;
} }
/** // /**
* Restful logging // * Restful logging
* // *
* @param restTemplateBuilder RestTemplateBuilder // * @param restTemplateBuilder RestTemplateBuilder
* @return RestTemplate // * @return RestTemplate
* @see RestTemplateLoggingRequestInterceptor // * @see RestTemplateLoggingRequestInterceptor
* @see RestTemplateLoggingRequestInterceptor // * @see RestTemplateLoggingRequestInterceptor
*/ // */
@Bean // @Bean
// @Qualifier("restTemplate") // @Qualifier("restTemplate")
public RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder) { // public RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder) {
//// return restTemplateBuilder
//// // 로깅 인터셉터에서 Stream을 소비하므로 BufferingClientHttpRequestFactory 을 꼭 써야한다.
//// .requestFactory(() -> new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory()))
//// // 타임아웃 설정 (ms 단위)
//// .setConnectTimeout(Duration.ofSeconds(CoreConstants.CONNECT_TIMEOUT))
//// .setReadTimeout(Duration.ofSeconds(CoreConstants.READ_TIMEOUT))
//// // UTF-8 인코딩으로 메시지 컨버터 추가
//// .additionalMessageConverters(new StringHttpMessageConverter(CoreConstants.CHARSET))
//// // 로깅 인터셉터 설정
//// .additionalInterceptors(new RestTemplateLoggingRequestInterceptor())
//// .build();
//
// return restTemplateBuilder // return restTemplateBuilder
// // 로깅 인터셉터에서 Stream을 소비하므로 BufferingClientHttpRequestFactory 을 꼭 써야한다. // .setReadTimeout(Duration.ofSeconds(XitConstants.READ_TIMEOUT))
// .requestFactory(() -> new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory())) // .setConnectTimeout(Duration.ofSeconds(XitConstants.CONNECT_TIMEOUT))
// // 타임아웃 설정 (ms 단위)
// .setConnectTimeout(Duration.ofSeconds(CoreConstants.CONNECT_TIMEOUT))
// .setReadTimeout(Duration.ofSeconds(CoreConstants.READ_TIMEOUT))
// // UTF-8 인코딩으로 메시지 컨버터 추가 // // UTF-8 인코딩으로 메시지 컨버터 추가
// .additionalMessageConverters(new StringHttpMessageConverter(CoreConstants.CHARSET)) // .messageConverters(new StringHttpMessageConverter(XitConstants.CHARSET))
// // 로깅 인터셉터 설정 // // 로깅 인터셉터 설정
// .additionalInterceptors(new RestTemplateLoggingRequestInterceptor()) // .interceptors(new RestTemplateLoggingRequestInterceptor())
// // 로깅 인터셉터에서 Stream을 소비하므로 BufferingClientHttpRequestFactory 을 꼭 써야한다.
// .customizers(restTemplate -> restTemplate.setRequestFactory(new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory())))
// .build(); // .build();
// }
return restTemplateBuilder
.setReadTimeout(Duration.ofSeconds(XitConstants.READ_TIMEOUT))
.setConnectTimeout(Duration.ofSeconds(XitConstants.CONNECT_TIMEOUT))
// UTF-8 인코딩으로 메시지 컨버터 추가
.messageConverters(new StringHttpMessageConverter(XitConstants.CHARSET))
// 로깅 인터셉터 설정
.interceptors(new RestTemplateLoggingRequestInterceptor())
// 로깅 인터셉터에서 Stream을 소비하므로 BufferingClientHttpRequestFactory 을 꼭 써야한다.
.customizers(restTemplate -> restTemplate.setRequestFactory(new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory())))
.build();
}
/** /**
* properties files yaml file * properties files yaml file

@ -92,7 +92,7 @@ public class DataSourceConfig {
return new JpaProperties(); return new JpaProperties();
} }
@Profile("!test") //@Profile("!test")
@Bean @Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(@Value("${spring.jpa.properties.hibernate.hbm2ddl.auto}") String hbm2ddlAuto) { public LocalContainerEntityManagerFactoryBean entityManagerFactory(@Value("${spring.jpa.properties.hibernate.hbm2ddl.auto}") String hbm2ddlAuto) {
// return builder // return builder
@ -236,28 +236,28 @@ public class DataSourceConfig {
//////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////
// Test // Test
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
@Profile("test") // @Profile("test")
@Bean // @Bean
public LocalContainerEntityManagerFactoryBean testManagerFactory(@Value("${spring.jpa.properties.hibernate.hbm2ddl.auto}") String hbm2ddlAuto) { // public LocalContainerEntityManagerFactoryBean testManagerFactory(@Value("${spring.jpa.properties.hibernate.hbm2ddl.auto}") String hbm2ddlAuto) {
//
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); // HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setDatabasePlatform(jpaProperties().getDatabasePlatform()); // vendorAdapter.setDatabasePlatform(jpaProperties().getDatabasePlatform());
vendorAdapter.setDatabase(jpaProperties().getDatabase()); // vendorAdapter.setDatabase(jpaProperties().getDatabase());
//
HibernateProperties hibernateProperties = new HibernateProperties(); // HibernateProperties hibernateProperties = new HibernateProperties();
hibernateProperties.setDdlAuto(hbm2ddlAuto); // hibernateProperties.setDdlAuto(hbm2ddlAuto);
Map<String, Object> propMap = hibernateProperties.determineHibernateProperties( // Map<String, Object> propMap = hibernateProperties.determineHibernateProperties(
jpaProperties().getProperties() // jpaProperties().getProperties()
, new HibernateSettings()); // , new HibernateSettings());
//
LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean(); // LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
emf.setDataSource(dataSource()); // emf.setDataSource(dataSource());
emf.setPackagesToScan(ENTITY_PACKAGES); // emf.setPackagesToScan(ENTITY_PACKAGES);
emf.setPersistenceUnitName("test"); // emf.setPersistenceUnitName("test");
emf.setJpaVendorAdapter(vendorAdapter); // emf.setJpaVendorAdapter(vendorAdapter);
emf.setJpaPropertyMap(propMap); //jpaProperties().getProperties()); // emf.setJpaPropertyMap(propMap); //jpaProperties().getProperties());
return emf; // return emf;
} // }
} }

@ -25,6 +25,7 @@ spring:
jdbc-url: ${spring.datasource.url} jdbc-url: ${spring.datasource.url}
username: ${spring.datasource.username} username: ${spring.datasource.username}
password: ${spring.datasource.password} password: ${spring.datasource.password}
read-only: false
# ================================================================================================================== # ==================================================================================================================
# JPA setting # JPA setting
@ -49,7 +50,6 @@ spring:
# thymeleaf: # thymeleaf:
# cache: false # cache: false
# ================================================================================================================== # ==================================================================================================================
# JPA logging lib setting # JPA logging lib setting
# ================================================================================================================== # ==================================================================================================================

@ -12,10 +12,10 @@ spring:
datasource: datasource:
driver-class-name: org.h2.Driver driver-class-name: org.h2.Driver
jdbc-url: jdbc:h2:mem:xitdb;MODE=PostgreSQL;DATABASE_TO_LOWER=TRUE;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE url: jdbc:h2:mem:xitdb;MODE=PostgreSQL;DATABASE_TO_LOWER=TRUE;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
username: sa username: sa
password: '' password: ''
hikari-test: hikari:
driver-class-name: ${spring.datasource.driver-class-name} driver-class-name: ${spring.datasource.driver-class-name}
jdbc-url: ${spring.datasource.url} jdbc-url: ${spring.datasource.url}
username: ${spring.datasource.username} username: ${spring.datasource.username}
@ -27,38 +27,10 @@ spring:
properties: properties:
hibernate: hibernate:
format_sql: true format_sql: true
#use_sql_comments: false use_sql_comments: false
hbm2ddl: hbm2ddl:
auto: create-drop auto: create-drop
# properties:
# order_inserts: true
# order_updates: true
# default_batch_fetch_size: ${chunkSize:100}
# current_session_context_class: org.springframework.orm.hibernate5.SpringSessionContext
# implicit_naming_strategy: org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy
# physical_naming_strategy: com.xit.core.config.support.LowercaseSnakePhysicalNamingStrategy
# hibernate:
# format_sql: true
# use_sql_comments: false
# hbm2ddl:
# auto: create-drop
# hbm2ddl:
# import_files_sql_extractor: org.hibernate.tool.hbm2ddl.MultipleLinesSqlCommandExtractor
# jdbc:
# batch_size: 20
# lob:
# # postgres 사용시 createLob() 미구현 경고 삭제
# non_contextual_creation: true
# # Jdbc 환경구성을 하는 과정에서 Default Metadata를 사용할 지 여부
# temp:
# use_jdbc_metadata_defaults: false
# thymeleaf:
# cache: false
decorator: decorator:
datasource: datasource:
p6spy: p6spy:

@ -1,6 +1,8 @@
spring: spring:
application: application:
name: xit-framework name: xit-framework
#description: XIT api for development
config: config:
import: classpath:config/conf.yml import: classpath:config/conf.yml
profiles: profiles:
@ -8,10 +10,7 @@ spring:
include: oauth include: oauth
# bean name 중복 허용 - junit 사용시 true?? # bean name 중복 허용 - junit 사용시 true??
main: main:
allow-bean-definition-overriding: false allow-bean-definition-overriding: true
# WebSecurity debug
security:
debug: true
# ================================================================================================================== # ==================================================================================================================
# spring message # spring message
@ -75,16 +74,34 @@ spring:
auto-commit: false auto-commit: false
# 인프라의 적용된 connection time limit보다 작아야함 # 인프라의 적용된 connection time limit보다 작아야함
max-lifetime: 1800000 max-lifetime: 1800000
maximum-pool-size: 50 maximum-pool-size: 30
minimum-idle: 50 minimum-idle: 5
transaction-isolation: TRANSACTION_READ_UNCOMMITTED transaction-isolation: TRANSACTION_READ_UNCOMMITTED
data-source-properties: data-source-properties:
rewriteBatchedStatements: true rewriteBatchedStatements: true
# ==================================================================================================================
# JTA setting
# ==================================================================================================================
# jta:
# enabled: true
# atomikos:
# datasource:
# #lw:
# unique-resource-name: xaForLegacyDataSource
# xa-data-source-class-name: com.mysql.cj.jdbc.MysqlXADataSource
# xa-properties:
# user:
# password:
# url: jdbc:mysql://localhost:3306/xit-framework?autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull
# ================================================================================================================== # ==================================================================================================================
# JPA setting # JPA setting
# ================================================================================================================== # ==================================================================================================================
jpa: jpa:
hibernate:
ddl-auto: none
# 템플릿 view 화면의 렌더링이 끝날 때 까지 Lazy fetch 가 가능하도록 해주는 속성 # 템플릿 view 화면의 렌더링이 끝날 때 까지 Lazy fetch 가 가능하도록 해주는 속성
open-in-view: false open-in-view: false
generate-ddl: false generate-ddl: false
@ -109,6 +126,7 @@ spring:
temp: temp:
use_jdbc_metadata_defaults: false use_jdbc_metadata_defaults: false
# jackson time setting # jackson time setting
jackson: jackson:
date-format: yyyy-MM-dd HH:mm:ss date-format: yyyy-MM-dd HH:mm:ss

@ -12,7 +12,9 @@ import com.xit.core.oauth2.api.dto.LoginRequestDto;
import com.xit.core.oauth2.api.dto.TokenDto; import com.xit.core.oauth2.api.dto.TokenDto;
import com.xit.core.oauth2.api.service.IAuthService; import com.xit.core.oauth2.api.service.IAuthService;
import com.xit.core.oauth2.oauth.entity.ProviderType; import com.xit.core.oauth2.oauth.entity.ProviderType;
import com.xit.core.oauth2.oauth.entity.RoleType;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.junit.Assert;
import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
@ -33,11 +35,13 @@ import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.ComponentScan;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.mock.web.MockServletContext;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MockMvcBuilder; import org.springframework.test.web.servlet.MockMvcBuilder;
import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.test.web.servlet.setup.MockMvcBuilders;
@ -47,6 +51,7 @@ import org.springframework.util.MultiValueMap;
import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter; import org.springframework.web.filter.CharacterEncodingFilter;
import javax.servlet.ServletContext;
import java.util.Arrays; import java.util.Arrays;
import java.util.UUID; import java.util.UUID;
@ -59,6 +64,8 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
//@RunWith(SpringRunner.class) //@RunWith(SpringRunner.class)
//@RunWith(MockitoJUnitRunner.class) //@RunWith(MockitoJUnitRunner.class)
@ExtendWith(SpringExtension.class) @ExtendWith(SpringExtension.class)
//@ContextConfiguration(classes = { ApplicationConfig.class })
@WebAppConfiguration
@WebMvcTest(controllers = OAuth2LocalController.class) @WebMvcTest(controllers = OAuth2LocalController.class)
//@SpringBootTest //@SpringBootTest
//@AutoConfigureMockMvc //@AutoConfigureMockMvc
@ -66,13 +73,18 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
class OAuth2LocalControllerTest { class OAuth2LocalControllerTest {
@Autowired @Autowired
MockMvc mocMvc; MockMvc mockMvc;
@Autowired
private WebApplicationContext webApplicationContext;
CmmUser user = CmmUser.builder() CmmUser user = CmmUser.builder()
.providerType(ProviderType.LOCAL) .providerType(ProviderType.LOCAL)
.userId("minuk926") .userId("minuk926")
.userName("임종욱") .userName("임종욱")
.password("Minuk926!@") .password("Minuk926!@")
.email("minuk926@gmail.com")
.build(); .build();
@ -80,8 +92,8 @@ class OAuth2LocalControllerTest {
//@InjectMocks //@InjectMocks
//private CmmUserMapstruct mapstruct = CmmUserMapstructImpl.INSTANCE; //private CmmUserMapstruct mapstruct = CmmUserMapstructImpl.INSTANCE;
//@Autowired @Autowired
//ICmmUserRepository userRepository; ICmmUserRepository userRepository;
//@Autowired //@Autowired
//ICmmRoleRepository roleRepository; //ICmmRoleRepository roleRepository;
@ -89,14 +101,18 @@ class OAuth2LocalControllerTest {
@BeforeEach @BeforeEach
void setUp() { void setUp() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.webApplicationContext).build();
CmmUser user = CmmUser.builder() CmmUser user = CmmUser.builder()
.providerType(ProviderType.LOCAL) .providerType(ProviderType.LOCAL)
.userId("minuk926") .userId("minuk926")
.userName("임종욱") .userName("임종욱")
.password("Minuk926!@") .password("Minuk926!@")
.email("minuk926@gmail.com")
.roleType(RoleType.USER)
.build(); .build();
user.setCmmUserId(UUID.randomUUID().toString().replaceAll("-", "")); user.setCmmUserId(UUID.randomUUID().toString().replaceAll("-", ""));
//CmmUser cmmUser = userRepository.save(user); CmmUser cmmUser = userRepository.save(user);
// userRepository.save(user); // userRepository.save(user);
} }
@ -109,11 +125,18 @@ class OAuth2LocalControllerTest {
@Test @Test
void login() throws Exception { void login() throws Exception {
ServletContext servletContext = webApplicationContext.getServletContext();
assertNotNull(servletContext);
assertTrue(servletContext instanceof MockServletContext);
assertNotNull(webApplicationContext.getBean("OAuth2LocalController"));
MultiValueMap<String, String> params = new LinkedMultiValueMap<>(); MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add("providerType", ProviderType.LOCAL.name()); params.add("providerType", ProviderType.LOCAL.name());
params.add("userId", "minuk926"); params.add("userId", "minuk926");
params.add("password", "Minuk926!@"); params.add("password", "Minuk926!@");
mocMvc.perform(post("/api/vi/auth/login").params(params)) mockMvc.perform(post("/api/vi/auth/login").params(params))
.andDo(print()) .andDo(print())
.andExpect(status().isOk()) .andExpect(status().isOk())
.andExpect(jsonPath("$.success").value(true)) .andExpect(jsonPath("$.success").value(true))

@ -0,0 +1,54 @@
package com.xit.core.repository.core;
import com.xit.biz.cmm.repository.ICmmUserRepository;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit.jupiter.SpringExtension;
@ExtendWith(SpringExtension.class)
@DataJpaTest
@ActiveProfiles(value = "dev")
public class CmmUserRepositoryTest {
@Autowired
private ICmmUserRepository cmmUserRepository;
// @Test
// public void saveUserTest() {
// User user = new User(null,"name", "password");
// User savedUser = userRepository.save(user);
// Assertions.assertEquals(user.getEmail(), savedUser.getEmail(),
// "saveUserTest");
// Assertions.assertEquals(user.getPassword(), savedUser.getPassword(),
// "saveUserTest");
// }
//
// @Test
// public void findByEmailSuccessTest() {
// User user = new User(null, "name1", "password");
// User savedUser = userRepository.save(user);
//
// Optional<User> userFindByEmail = userRepository.findByEmail(user.getEmail());
// userFindByEmail.ifPresent(value -> Assertions.assertEquals(savedUser.getEmail(), value.getEmail()));
// }
//
// @Test
// public void findByEmailFailureTest() {
//
// Optional<User> userFindByEmail = userRepository.findByEmail("not exist email");
// Assertions.assertEquals(Optional.empty(), userFindByEmail);
// }
//
// @Test
// public void idStrategyTest() {
// User user1 = new User(null, "name1", "password");
// User user2 = new User(null,"name2", "password");
// User savedUser1 = userRepository.save(user1);
// User savedUser2 = userRepository.save(user2);
//
// Assertions.assertEquals(1, Math.abs(savedUser1.getId() - savedUser2.getId()));
//
// }
}

@ -0,0 +1,96 @@
package com.xit.core.service.core;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
@ExtendWith(MockitoExtension.class)
public class OAuthLocalServiceTest {
// @Mock
// private UserRepository userRepository;
//
// @InjectMocks
// private UserService userService = new UserServiceImpl(this.userRepository);
// @Test
// void addUserSuccessfully() {
// final User user = new User(null, "name", "password");
// given(userRepository.findByEmail(user.getEmail())).willReturn(Optional.empty());
// given(userRepository.save(user)).willReturn(user);
//
// User savedUser = userService.add(user);
// Assertions.assertNotNull(savedUser);
// verify(userRepository).findByEmail(anyString());
// verify(userRepository).save(any(User.class));
// }
//
// @Test
// void addUserFailure() {
// final User user = new User(1L, "name", "password");
// given(userRepository.findByEmail(user.getEmail())).willReturn(Optional.of(user));
// Assertions.assertThrows(UserNotFoundException.class, () -> userService.add(user));
// verify(userRepository, never()).save(any(User.class));
// }
//
// @Test
// void getUserSuccessfully() {
// final User user = new User(1L, "name", "password");
// given(userRepository.findById(user.getId())).willReturn(Optional.of(user));
// User userByGet = userService.get(user.getId());
// Assertions.assertEquals(user, userByGet);
// verify(userRepository).findById(anyLong());
// }
//
// @Test
// void getUserFailure() {
// given(userRepository.findById(anyLong())).willReturn(Optional.empty());
// Assertions.assertThrows(UserNotFoundException.class, () -> userService.get(anyLong()));
// verify(userRepository).findById(anyLong());
// }
//
// @Test
// void updateSuccessfully() {
// final User user = new User(1L, "name", "password");
// given(userRepository.findById(user.getId())).willReturn(Optional.of(user));
// given(userRepository.save(user)).willReturn(user);
// User updatedUser = userService.update(user);
// Assertions.assertNotNull(updatedUser);
// verify(userRepository).save(any(User.class));
// }
//
// @Test
// void updateFailure() {
// final User user = new User(1L, "name", "password");
// given(userRepository.findById(anyLong())).willReturn(Optional.empty());
// Assertions.assertThrows(UserNotFoundException.class, () -> userService.update(user));
// verify(userRepository).findById(anyLong());
// }
//
// @Test
// void deleteSuccessfully() {
// final Long id = 1L;
// userService.delete(id);
// verify(userRepository, times(1)).deleteById(anyLong());
// verify(userRepository, times(1)).findById(anyLong());
//
// }
//
// @Test
// void findByEmailSuccessfully() {
// final User user = new User(1L, "name", "password");
// given(userRepository.findByEmail(user.getEmail())).willReturn(Optional.of(user));
// User userByEmail = userService.findByEmail(user.getEmail());
// Assertions.assertEquals(user, userByEmail);
// verify(userRepository).findByEmail(any(String.class));
// }
//
// @Test
// void findByEmailFailure() {
// final String email = "email";
// given(userRepository.findByEmail(email)).willReturn(Optional.empty());
// Assertions.assertThrows(UserNotFoundException.class, () -> userService.findByEmail(email));
// verify(userRepository).findByEmail(any(String.class));
// }
}
Loading…
Cancel
Save