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-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-jdbc'
// jta module
//implementation('org.springframework.boot:spring-boot-starter-jta-atomikos')
// yaml lib
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-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.hamcrest:hamcrest-library:2.2'
testRuntimeOnly 'com.jayway.jsonpath:json-path:2.5.0'
implementation 'org.assertj:assertj-core:3.21.0'
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.support.RestTemplateLoggingRequestInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.MessageSource;
@ -266,40 +267,40 @@ public class WebCommonConfig extends AsyncConfigurerSupport implements WebMvcCon
return executor;
}
/**
* Restful logging
*
* @param restTemplateBuilder RestTemplateBuilder
* @return RestTemplate
* @see RestTemplateLoggingRequestInterceptor
* @see RestTemplateLoggingRequestInterceptor
*/
@Bean
//@Qualifier("restTemplate")
public RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder) {
// /**
// * Restful logging
// *
// * @param restTemplateBuilder RestTemplateBuilder
// * @return RestTemplate
// * @see RestTemplateLoggingRequestInterceptor
// * @see RestTemplateLoggingRequestInterceptor
// */
// @Bean
// @Qualifier("restTemplate")
// 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
// // 로깅 인터셉터에서 Stream을 소비하므로 BufferingClientHttpRequestFactory 을 꼭 써야한다.
// .requestFactory(() -> new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory()))
// // 타임아웃 설정 (ms 단위)
// .setConnectTimeout(Duration.ofSeconds(CoreConstants.CONNECT_TIMEOUT))
// .setReadTimeout(Duration.ofSeconds(CoreConstants.READ_TIMEOUT))
// .setReadTimeout(Duration.ofSeconds(XitConstants.READ_TIMEOUT))
// .setConnectTimeout(Duration.ofSeconds(XitConstants.CONNECT_TIMEOUT))
// // 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();
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

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

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

@ -12,10 +12,10 @@ spring:
datasource:
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
password: ''
hikari-test:
hikari:
driver-class-name: ${spring.datasource.driver-class-name}
jdbc-url: ${spring.datasource.url}
username: ${spring.datasource.username}
@ -27,37 +27,9 @@ spring:
properties:
hibernate:
format_sql: true
#use_sql_comments: false
use_sql_comments: false
hbm2ddl:
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:
datasource:

@ -1,6 +1,8 @@
spring:
application:
name: xit-framework
#description: XIT api for development
config:
import: classpath:config/conf.yml
profiles:
@ -8,10 +10,7 @@ spring:
include: oauth
# bean name 중복 허용 - junit 사용시 true??
main:
allow-bean-definition-overriding: false
# WebSecurity debug
security:
debug: true
allow-bean-definition-overriding: true
# ==================================================================================================================
# spring message
@ -75,16 +74,34 @@ spring:
auto-commit: false
# 인프라의 적용된 connection time limit보다 작아야함
max-lifetime: 1800000
maximum-pool-size: 50
minimum-idle: 50
maximum-pool-size: 30
minimum-idle: 5
transaction-isolation: TRANSACTION_READ_UNCOMMITTED
data-source-properties:
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:
hibernate:
ddl-auto: none
# 템플릿 view 화면의 렌더링이 끝날 때 까지 Lazy fetch 가 가능하도록 해주는 속성
open-in-view: false
generate-ddl: false
@ -108,6 +125,7 @@ spring:
# Jdbc 환경구성을 하는 과정에서 Default Metadata를 사용할 지 여부
temp:
use_jdbc_metadata_defaults: false
# jackson time setting
jackson:

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