Skip to content
This repository has been archived by the owner on Aug 13, 2022. It is now read-only.

#36 junit 이용한 테스트 코드 작성 #37

Open
wants to merge 18 commits into
base: feature/30
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,12 @@ USECASE
- 관리자
- 관리자는 회원관리를 위해 구매자/판매자의 상태를 관리 할 수있다.

테스트
---
- Mockito Framework를 활용하여 고립된 테스트 코드를 작성
- Jenkins CI를 적용하여 테스트 자동화
- 협업하는 동료의 소스코드에 서로 테스트코드를 작성하여 서로의 소스코드를 알 수 있도록 하고 있습니다.

ERD
---
![UsedMarket_24_20200730_39_51](https://user-images.githubusercontent.com/61732452/88840524-98ed7100-d217-11ea-9b76-8043edc17326.png)
14 changes: 0 additions & 14 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -49,12 +49,6 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>mysql</groupId>
Expand Down Expand Up @@ -99,13 +93,6 @@
<artifactId>spring-session-data-redis</artifactId>
</dependency>

<!-- Junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>

<!-- AOP -->
<dependency>
<groupId>org.springframework.boot</groupId>
Expand Down Expand Up @@ -148,7 +135,6 @@
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.3.1.RELEASE</version>
</plugin>
</plugins>
<resources>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ public void updateProducts(ProductDTO productDTO) {
public void deleteProduct(int accountId, int productId) {
if (accountId != 0 && productId != 0) {
productMapper.deleteProduct(accountId, productId);
if(productDao.selectProductsIndex(productId)!=0)
productId = productDao.selectProductsIndex(productId);
if (productDao.deleteByProductIdAndIndex(ProductDTO.DEFAULT_PRODUCT_SEARCH_CACHE_KEY, productId) == false) {
throw new RuntimeException("물품 레디스 리스트에서 삭제 실패!");
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/com/market/server/utils/DateUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ public class DateUtil {
* @return 처리 시간의 문자열 202009040159.jpg
* @author topojs8
*/
private static ThreadLocal<SimpleDateFormat> getNowTimeToyyyyMMddHHmm = new ThreadLocal<SimpleDateFormat>() {
private static final ThreadLocal<SimpleDateFormat> getNowTimeToyyyyMMddHHmm = new ThreadLocal<SimpleDateFormat>() {
@Override
protected SimpleDateFormat initialValue() {
return new SimpleDateFormat("yyyyMMddHHmm");
Expand Down
14 changes: 9 additions & 5 deletions src/main/resources/application-release.properties
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# mysql
spring.datasource.url=jdbc:mysql://localhost:3307/market?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Seoul
spring.datasource.username=root
spring.datasource.password=wnstjr1026
spring.datasource.url=jdbc:mysql://10.41.82.248:3306/market?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Seoul
spring.datasource.username=topojs
spring.datasource.password=1234

# message
spring.messages.basename=i18n/exception
Expand All @@ -10,10 +10,14 @@ spring.messages.encoding=UTF-8
# redis
spring.cache.type=redis
spring.data.redis.repositories.enabled=true
market.server.redis.host=localhost
market.server.redis.host=10.41.83.37
market.server.redis.port=6379
market.server.redis.password=

# expire
expire.defaultTime=36288000
expire.products=5
expire.products=5000

#JSP, HTML ModelAndView Path Setting
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
4 changes: 2 additions & 2 deletions src/main/resources/application.properties
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
# Server
server.port=
server.port=8080

# profile name = local, dev, prod
spring.profiles.active=dev
spring.profiles.active=release

# session
spring.session.store-type=redis
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
//@RunWith(SpringRunner.class)
class UsedMarketServerApplicationTests {

@Test
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
package com.market.server.service.Impl;

import com.market.server.dao.ProductDao;
import com.market.server.dto.CategoryDTO;
import com.market.server.dto.ProductDTO;
import com.market.server.mapper.CategoryMapper;
import com.market.server.mapper.ProductMapper;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.junit.MockitoJUnitRunner;

import java.util.Date;
import java.util.List;

import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.BDDMockito.given;

@RunWith(MockitoJUnitRunner.class)
class CategoryServiceImplTest {

@InjectMocks
CategoryServiceImpl categoryService;

@Mock
CategoryMapper categoryMapper;

// 새로운 카테고리 객체를 생성하여 반환한다.
public CategoryDTO generateCategory() {
MockitoAnnotations.initMocks(this); // mock all the field having @Mock annotation
CategoryDTO categoryDTO = CategoryDTO.builder()
.id(1)
.name("testName")
.sortStatus(CategoryDTO.SortStatus.NEWEST)
.searchCount(1000)
.pagingStartOffset(0)
.build();
return categoryDTO;
}

@Test
void register() {
CategoryDTO categoryDTO = generateCategory();
given(categoryMapper.register(categoryDTO)).willReturn(categoryDTO.getId());
categoryMapper.register(categoryDTO);
}

@Test
void update() {
CategoryDTO categoryDTO = generateCategory();
categoryDTO.setName("testName2");
categoryMapper.updateCategory(categoryDTO);
assertEquals(categoryDTO.getName(),("testName2"));
}

@Test
void delete() {
CategoryDTO categoryDTO = generateCategory();
categoryDTO.setId(1);
categoryMapper.deleteCategory(1);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
package com.market.server.service.Impl;

import com.market.server.dao.ProductDao;
import com.market.server.dto.CategoryDTO;
import com.market.server.dto.ProductDTO;
import com.market.server.dto.UserDTO;
import com.market.server.mapper.ProductMapper;
import com.market.server.utils.SHA256Util;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.junit.MockitoJUnitRunner;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.BDDMockito.given;

@RunWith(MockitoJUnitRunner.class)
class ProductSearchServiceImplTest {

@InjectMocks
ProductServiceImpl productService;

@InjectMocks
ProductSearchServiceImpl productSearchService;

@Mock
ProductMapper productMapper;

@Mock
ProductDao productDao;

// 새로운 물품 객체 리스트를 생성하여 반환한다.
public List<ProductDTO> generateProductList() {
MockitoAnnotations.initMocks(this); // mock all the field having @Mock annotation
List<ProductDTO> productDTOList = new ArrayList<ProductDTO>();
for (int i = 0; i < 5; i++) {
ProductDTO productDTO = ProductDTO.builder()
.id(i)
.price(1000)
.accountId(1)
.title("testProductTitle")
.contents("testProductContents")
.status(ProductDTO.Status.NEW)
.istrade(true)
.updatetime(new Date())
.deliveryprice(3000)
.dibcount(1)
.categoryId(1)
.build();
productDTOList.add(productDTO);
}
return productDTOList;
}

public UserDTO generateUser() {
UserDTO userDTO = new UserDTO();
userDTO.setId("textUserId");
userDTO.setPassword(SHA256Util.encryptSHA256("testPassword"));
userDTO.setName("testUserName");
userDTO.setPhone("010-1111-2222");
userDTO.setAddress("testAdress");
userDTO.setStatus(UserDTO.Status.DEFAULT);
userDTO.setCreatetime(new Date());
userDTO.setUpdatetime(new Date());
userDTO.setAddmin(false);
userDTO.setAccountId(1);
return userDTO;
}

@Test
void findAllProductsByCacheId() {
MockitoAnnotations.initMocks(this); // mock all the field having @Mock annotation
UserDTO userDTO = generateUser();
productDao.findAllProductsByCacheId(userDTO.getId());
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

findAllProductsByCacheId 내부에서 일어나는 로직 검사라던지 리턴값이라던지 그런 스펙에 대한 검사가 없네요~

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Mock
private RedisTemplate<String, Object> redisTemplate;

@Mock
private ValueOperations valueOperations;

선언 후에
redisTemplate.opsForList().rightPush(ProductDTO.DEFAULT_PRODUCT_SEARCH_CACHE_KEY, productDTO);
여기서 redisTemplate이 mock객체로 null은 아니지만 List,push 할때 null객체로 에러가 납니다.
접근을 어떻게 해야 할까요??

}

@Test
void getProducts() {
List<ProductDTO> productDTOList = generateProductList();
given(productMapper.selectMyProducts(1)).willReturn(productDTOList);
given(productMapper.selectMyProducts(999)).willReturn(null);
productMapper.selectMyProducts(1);

UserDTO userDTO = generateUser();
productService.getMyProducts(userDTO.getAccountId());
}
}
Loading