728x90
300x250

[Spring-Framework] 23(번외). STS 4.4 - Spring Boot Starter - 배포(Jar, War방식)


이전의 글을 참고하여 진행하면 될 것 같다.

Spring Boot Starter의 배포 방식에는 크게 "Jar", "War"로 구성된다.

Spring Boot Starter의 Jar파일 배포는 maven Build를 통해서 이뤄진다.

내장 톰캣 웹서버까지 함께 배포해버리는 단점이 있다.

차이점이 Spring Legacy Project로 생성한 Spring Framework는 일반적인 배포에서는 간단하게 War 배포를 할 수 있다.


- IDE: Spring Tool-Suite 4-4.7.2 Releases (2020-06-29 기준 최신 버전) // 대략



1. Spring Boot Starter - 배포 방법 JAR


Jar 방식으로 배포하는 방법에 대해서 소개하겠다.



그림 1. Run에서 Maven Build하기


(작업하고 있는) Spring Boot 프로젝트를 선택한다.

Run 메뉴를 클릭한다.

Run As에서 5 Maven Build...를 클릭한다. (은근히 햇갈리게 되어 있음.)



그림 2. Run에서 Maven Build하기

Goals에 package

Profiles은 비워둔다.

Run 버튼을 누른다.




그림 3. 빌드 기다리는 모습(1)


시간이 걸린다. 다운로드 과정 등이 있다. 알아서 배포 작업이 잘 되고 있는지 태스트 작업도 하고 그렇다.



그림 4. 빌드 기다리는 모습(2)



그림 5. 빌드 완료된 모습(1)


BUILD SUCCESS라고 뜨면 잘 된 것이다. 빨강색 뜨면 안 좋은 것이다. (오류도 잡아야 하고 그렇다. ㅠㅠ)



그림 6. 빌드 완료된 모습(2)


console 대화창 내용을 클릭한다.

Ctrl + F를 누른다.

jar를 검색한다.


무슨 파일명으로 배포되었는지 알기 위해서이다.



그림 7. 빌드 완료된 모습(3)


프로젝트 창을 F5키로 새로고침한다.

target 폴더를 클릭해보면, 배포된 파일을 살펴볼 수 있다.



그림 8. 빌드 완료된 모습(4)


쉬워보여도 쉬운 과정이 아니다. 또 실제 서버에 빌드해서 태스트를 해야 한다.

또 안 되면, 다시 Eclipse 작업창에서 삽질을 해야 한다.



2. Spring Boot Starter - 배포 방법 War


war 배포 방법은 다소 어렵다. 코드 몇 줄이긴 하지만, 작성해줘야 한다.

코드 부분도 소개하도록 하겠다.



2-1. war 배포 - pom.xml


pom.xml 수정에 대한 사항이다.



그림 9. pom.xml 파일 수정(1) - 변경해야 할 내용



그림 10. pom.xml 파일 수정(2) - 변경해야 할 내용



그림 11. pom.xml 파일 수정(2) - 변경해야 할 내용


아래의 내용을 열어보면, 확인할 수 있다. (굵기 표시로 변경 작업을 한 내역을 표시하였음.)





2-2. War 배포 - SpringBootMvcDemoApplication.java


사소해보이지만, 코드 변경이 중요하다.

이거 안 해주면, pom.xml 설정 잘 되어 있어도 오류가 뜬다.



그림 12. pom.xml 파일 수정(2) - 변경해야 할 내용


package com.springmvc.home;


import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.boot.builder.SpringApplicationBuilder;

import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;


@SpringBootApplication

public class SpringBootMvcDemoApplication extends SpringBootServletInitializer {


public static void main(String[] args) {

//SpringApplication.run(SpringBootMvcDemoApplication.class, args);

SpringApplication app = new SpringApplication(SpringBootMvcDemoApplication.class);

app.run(args);

}


@Override

protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {

return builder.sources(SpringBootMvcDemoApplication.class);

}


}



파일명: SpringBootMvcDemoApplication.java


[첨부(Attachments)]

SpringBootMvcDemoApplication.zip





2-3. Run As로 Maven Build하기 - War 배포


지금부터 작업은 배포를 하는 것이다.



그림 13. Run의 Maven build 메뉴 모습


Run 메뉴를 클릭한다.

Run As의 Maven build를 클릭한다.




그림 14. Select Configuration


SpringBootMVCDemo (1) : package를 선택하고 OK를 누른다.




그림 15. 빌드가 완료된 모습


빌드하는 데 시간이 다소 소요된다.

기다리면 된다.


BUILD SUCCESS라고 녹색 대화 글이 나오면 잘 된 것이다.



2-4. 톰캣 서버에 올리기 - war 배포


웹 서버에 실제로 배포하는 방법에 대해서 소개하겠다.








그림 16. 빌드가 완료된 파일 (1)


demo-0.0.1-SNAPSHOT.war 파일을 선택한다.

복사한다. (Ctrl + C)




그림 17. 톰캣 서버의 webapps 폴더에 넣어주기 (2)


톰캣 서버 설치 경로의 webapps에 들어간다.

붙여넣기를 한다. (Ctrl + V)




그림 18. 톰캣 서버의 bin - startup 실행해주기


bin폴더에서 startup.bat을 더블 클릭한다.

서버를 실행해준다.




그림 19. 서버가 실행되고 나면, 압축해제가 된 모습


정상적으로 폴더가 생성되었다면, 배포가 잘 된 것이다.




그림 20. 서버 실행 모습


Tomcat 서버에 보면, 익숙한 모습으로 Spring Security 생성 암호가 있다.

Using generated security password:의 내용을 복사한다.


Username: User

Password: 복사한 내용의 비밀번호(암호화된 랜덤 형태의 암호이다)




그림 21. 로그인 후 배포된 모습


정상적으로 화면이 보인다면, 배포가 성공적으로 이뤄진 것이다.



3. 결론(Conclusion)


서버 배포 작업도 개발자라면 경험해봐야 할 중요한 부분이라고 생각된다.

다소 스프링 부트는 배포 부분에 있어서는 쉽지만 않다.


서버 배포에 대해서 살펴보았고, Jar파일로 배포하는 방법에 대해서도 소개하였다.



* 참고자료(References)


1. [스프링 부트] war 파일과 외부 톰캣을 이용한 서버 배포, https://steady-hello.tistory.com/53, Accessed by 2020-09-30, Last Modified 2019-10-30.

반응형
728x90
300x250

[Spring-Framework] 22(번외). STS 4.4 - Spring Boot Starter - MyBatis(Boot용), HikariCP 3.4 사용하기


이전의 JSP/servlet의 myBatis 글과 Spring Framework를 활용하여 HikariCP를 적용한 프로젝트를 소개한 적이 있다.

이 글들에 이어서 소개하려고 한다.


IDE: Spring-Tool-Suite 4-4.7.2 Releases
     - MyBatis Spring Boot Starter » 2.1.3(2020-06-05)  // pom.xml에서 이거 하나만 해주면 설치 끝남.


이 글을 읽으려면, 기존의 MyBatis 사용과는 조금 차이를 두고 구현해야 한다. (Spring Boot Starter 버전이 따로 있음.)
- 고정 관념을 먼저 깨줘야 한다.


이 글을 읽고 따라해보면, 개발에 있어서 상상 초월의 퍼포먼스를 경험할 수 있을 거라고 본다.





1. 구축하는 데 원리만 제대로 알게 되면, 매우 쉽다.


할 일이 크게 없어져버렸다고 보면 된다.

책도 많이 없을 뿐더러 자료가 다소 부족해서 그렇지만, 알게 되면 무슨 DB구축이 이렇게나 쉽냐고 당황할 수 있는 수준이라고 표현하고 싶다.


이 블로그 운영자인 필자가 자랑하는 것이 아니라, 최신 버전으로 가면 갈수록 할 게 없다. 

(커넥션 풀도 내장되어 있고, 영속 프레임워크도 기본 내장되어 있다. 굳이 JPA나 각종 Hibernate를 찾을 필요가 있는지 이런 생각이 들 정도이다.)


자료가 없어서 삽질을 다소 했지만, 진짜 쉬워졌다. 현재의 Spring Starter만 잘 활용하면, 많은 거 신경 쓸 필요가 전혀 없고, DB하고(SQL문법 등) 개발만 집중하면 된다. 아이디어만 잘 짜내서, 좋은 서비스 찍어내면 된다.(희망사항이긴 하지만.)




그림 1. 프로젝트 구성도  (Spring Boot Starer 프로젝트)


xml 맵핑 복잡하게 그런 것도 할 필요가 없어졌다.



2. 결과


REST Controller를 활용해서 JSON형태로 출력하였다.

잘 된다.


소스코드 양도 훨씬 줄었다. HikariCP하고, MyBatis Framework가 기본으로 Spring Boot에서는 사용된다고 보면 된다.



그림 2. 완성된 작업물




3. 데이터베이스 설계


먼저 DB설계를 하는 건 결코 아니다. 해당 작업을 조금 원할하게 따라할 수 있도록 미리 소개하는 것이다.

Spring Security에서 제시하는 기본 USER(회원)에 관한 설계를 인용하였다.



그림 3. COMP_USERS - Spring Security 사용자 계정



CREATE TABLE comp_users (

username VARCHAR(50) NOT NULL,

password VARCHAR(300) NOT NULL,

enabled INT NOT NULL,

PRIMARY KEY (username)

);



-- 계정

INSERT INTO comp_users (username, password, enabled) VALUES ('user', '$2a$10$x04djNV2e9rpcPPRyXoLk.rMm6iZe2/vYdzpqHQcLeNSYdt7kc30O', 1);

INSERT INTO comp_users (username, password, enabled) VALUES ('admin', '$2a$10$QUddY3O/6ZgkYCR6MFlv9.nqA501Fm0cc/ZxQHX5pwb1o0CYCTiIS', 1);


파일명: comp_users.sql


[첨부(Attachments)]

comp_user.zip




4. 프로젝트 생성하기


프로젝트 생성은 매우 간단한 방법으로 진행된다. 인터넷이 되는 환경에서 작업을 해야 한다.



그림 3. 스프링 스타터 프로젝트(1)


프로젝트 익스플로러의 빈칸에서 오른쪽 버튼을 클릭한다.

Spring Starter Project를 클릭한다.



그림 4. 스프링 스타터 프로젝트(2)


자바 버전부터 왠만한 내용은 자동으로 입력되어 있다.

환경에 맞춰서 클래스명, 그룹, Artifact 등 입력해준다.

Next를 클릭한다.


방식이 두 가지로 확장됨: Maven, Gradle 방식
- 안드로이드 스튜디오를 경험해봤으면, Gradle 방식을 접했을 수도 있다.

  Maven으로 선택한다.

  (이런 부분도 있어서 Spring Boot에 대해서 또 관심을 가져야 한다. Gradle 방식도 있기 때문이다.) 





그림 5. 스프링 스타터 프로젝트(3)


MyBatis가 내장되어 있는지, HikariCP가 내장되어 있는지 궁금하다면, "Type to search dep...."에 검색을 해보면 된다.

내장되어 있다고 나온다.


그래서 선택할 항목이 크게 많지는 않고, "MySQL Driver", "Oracle Driver", "Spring Security", "Spring Web"을 체크하였다.


참고로 작업을 진행할 때, Spring Security에 대해서 조금 익숙치 않은 경우라면, 체크를 해제해도 무방하다. 

(보안이 워낙 강해서 URL Mapping까지도 Spring Security에서 전부 제어해버리는 일이 발생하기 때문이다.)




그림 6. 스프링 스타터 프로젝트(4)



2. pom.xml 설정하기


pom 설정을 해줘야 하는 부분은 myBatis-starter 하나만 해주면 끝난다.

http://mvnrepository.com 

이 사이트가 중요하다.


Spring-Framework를 활성화 하는데 가장 큰 공헌을 한 사이트인 것 같다.




그림 6-1. MyBatis Spring Boot Starter 2.1.3 (MVNRepository.com)



 

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">

<modelVersion>4.0.0</modelVersion>

<parent>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-parent</artifactId>

<version>2.4.0-SNAPSHOT</version>

<relativePath/> <!-- lookup parent from repository -->

</parent>

<groupId>com.springmvc.home</groupId>

<artifactId>demo</artifactId>

<version>0.0.1-SNAPSHOT</version>

<name>SpringBootMVCDemo</name>

<description>Demo project for Spring Boot</description>


<properties>

<java.version>15</java.version>

</properties>


<dependencies>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-data-jdbc</artifactId>

</dependency>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-jdbc</artifactId>

</dependency>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-security</artifactId>

</dependency>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-web</artifactId>

</dependency>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-web-services</artifactId>

</dependency>


<dependency>

<groupId>com.oracle.database.jdbc</groupId>

<artifactId>ojdbc8</artifactId>

<scope>runtime</scope>

</dependency>

<dependency>

<groupId>mysql</groupId>

<artifactId>mysql-connector-java</artifactId>

<scope>runtime</scope>

</dependency>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-test</artifactId>

<scope>test</scope>

</dependency>

<dependency>

<groupId>org.springframework.security</groupId>

<artifactId>spring-security-test</artifactId>

<scope>test</scope>

</dependency>

<!-- Spring 부트에서는 이거 쓰면 안 됨 -->

<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->

<!-- 

<dependency>

    <groupId>org.mybatis</groupId>

    <artifactId>mybatis</artifactId>

    <version>3.5.5</version>

</dependency>

-->

<!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->

<dependency>

    <groupId>org.mybatis.spring.boot</groupId>

    <artifactId>mybatis-spring-boot-starter</artifactId>

    <version>2.1.3</version>

</dependency>


</dependencies>


<build>

<plugins>

<plugin>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-maven-plugin</artifactId>

</plugin>

</plugins>

</build>


<repositories>

<repository>

<id>spring-milestones</id>

<name>Spring Milestones</name>

<url>https://repo.spring.io/milestone</url>

</repository>

<repository>

<id>spring-snapshots</id>

<name>Spring Snapshots</name>

<url>https://repo.spring.io/snapshot</url>

<snapshots>

<enabled>true</enabled>

</snapshots>

</repository>

</repositories>

<pluginRepositories>

<pluginRepository>

<id>spring-milestones</id>

<name>Spring Milestones</name>

<url>https://repo.spring.io/milestone</url>

</pluginRepository>

<pluginRepository>

<id>spring-snapshots</id>

<name>Spring Snapshots</name>

<url>https://repo.spring.io/snapshot</url>

<snapshots>

<enabled>true</enabled>

</snapshots>

</pluginRepository>

</pluginRepositories>


</project>



파일명: pom.xml


[첨부(Attachments)]

pom.zip




3. application.properties 설정하


application.properties 설정 파일을 설정해줘야 한다.



그림 7. application.properties 설정하기


spring.datasource.driverClassName=oracle.jdbc.driver.OracleDriver

#org.mariadb.jdbc.Driver

spring.datasource.url=jdbc:oracle:thin:@127.0.0.1:1521:orcl

#jdbc:mariadb://localhost:3306/test?characterEncoding=UTF-8&serverTimezone=UTC

spring.datasource.username=user

spring.datasource.password=password


파일명: application.properties


[첨부(Attachments)]

application.zip



이 설정 하나면, 나머지 DataSource 등 설정까지 자동 인식함.
-> 글의 맨 마지막에 Spring-Legacy Project와의 차이점을 소개하겠음. (간단하게 이야기하면, 지탱해주고 있는 라이브러리가 많아졌다.)





3. RestStarterController.java - Controller


그냥 바로 컨트롤러 작업하면 된다. 설명을 해주고 싶어도 너무 간단한 구성이어서 그렇다.

공식 사이트 예제 참고해서 다소 변경한 것이다.


https://github.com/mybatis/spring-boot-starter

공식 스타터 홈페이지를 찾는데 시간이 다소 소요되었다는 것 빼고는 쉽게 되어 있다.


package com.springmvc.home.controller;


import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.PathVariable;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;


import com.springmvc.home.mapper.CompUserMapper;

import com.springmvc.home.model.CompUser;


@RestController

@RequestMapping("/cities")

public class RestStarterController {

private final CompUserMapper compUserMapper;


public RestStarterController(CompUserMapper compUserMapper) {

this.compUserMapper = compUserMapper;

}


@GetMapping("{state}")

CompUser getCompUser(@PathVariable String state) {

CompUser user = compUserMapper.findByUsername(state);

System.out.println("계정명:" + user.getUsername());

  return compUserMapper.findByUsername(state);

  

}


}


파일명: RestStarterController.java


[첨부(Attachments)]

RestStarterController.zip



4. CompUser.java - Model


데이터베이스 설계한 내용을 그대로 해줘야 한다.

이전의 사용방법처럼 어노테이션이나 이런 거 전혀 할 필요가 전혀 없다.

자동으로 맵핑이 된다.


package com.springmvc.home.model;


public class CompUser {

private String username;

private String password;

private int enabled;

public String getUsername() {

return username;

}

public void setUsername(String username) {

this.username = username;

}

public String getPassword() {

return password;

}

public void setPassword(String password) {

this.password = password;

}

public int getEnabled() {

return enabled;

}

public void setEnabled(int enabled) {

this.enabled = enabled;

}

}



파일명: CompUser.java


[첨부(Attachments)]

CompUser.zip




5. CompUserMapper.java - DAO 또는 Service에 해당됨.(Mapper)


진정한 생산성이라는 것을 느낄 수 있다.


package com.springmvc.home.mapper;


import org.apache.ibatis.annotations.Mapper;

import org.apache.ibatis.annotations.Select;


import com.springmvc.home.model.CompUser;


@Mapper

public interface CompUserMapper {

@Select("select * from comp_users where username = #{username}")

public CompUser findByUsername(String username);


}



파일명: CompUserMapper.java


[첨부(Attachments)]

CompUserMapper.zip



6. 어떤 이유 때문에 Spring Boot가 라이브러리가 많다는 건가요?


쉬워진 만큼 무언가 지탱해주고 있는 프로그램이 있다.


패키지명: com.springmvc.home

파일명: SpringBootApplication.java (자동 생성된 파일)


package com.springmvc.home;


import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;


@SpringBootApplication

public class SpringBootMvcDemoApplication {


public static void main(String[] args) {

SpringApplication.run(SpringBootMvcDemoApplication.class, args);

}


}



파일명: SpringBootMvcDemoApplication.java


Spring Boot는 특이한 점이 프로그램 형태로 실행을 시켜버린다.



그림 8, 그림 9, 그림 10. Spring Boot를 지탱해주는 기본 library


다소 양이 많다는 것을 알 수 있다.

쉬워진 개발환경만큼 지탱해주고 있는 jar파일은 매우 많이 늘어났다는 것이다.


자세히 깨알같은 글자를 보면,

- ojdbc-18-19.7 (Oracle JDBC 19.7)

- MySQL (8.0.21)

- spring web 5.3 RC

......


최신 라인 구성을 자랑하고 있다고 보면 된다.




7. 스프링 부트와 스프링 프레임워크의 MyBatis 차이점


간단하게 요약해보았다.



그림 11. 차이점 비교


구현에 있어서 훨씬 간단해졌다는 것이다.


[첨부(Attachments)]

mybatis-summary.zip





* 맺음글(Conclusion)


조금 당황스럽긴 하지만, 이게 글의 끝이다.

Spring Boot Starter의 DB, 커넥션 풀까지 함께 소개한 것이다. 환경 설정 몇 가지만 더 알게 되면 된다.

현재에도 Spring Legacy Project 방식으로 구현하는 이유가 있을 것으로 보인다. Spring Boot는 결과적으로는 사용하는 데 있어서 매우 간편해졌다.



* 참고자료(References)


1. Spring Boot and iBatis with H2 - A Tutorial, https://www.springboottutorial.com/spring-boot-and-iBatis-with-h2-tutorial, Accessed by 2020-09-30, Last Modified 2020-07-07.


[Spring Boot 버전의 MyBatis 핵심 사용법]


@Mapper

public interface StudentMyBatisRepository {

@Select("select * from student")

public List<Student> findAll();


@Select("SELECT * FROM student WHERE id = #{id}")

public Student findById(long id);


@Delete("DELETE FROM student WHERE id = #{id}")

public int deleteById(long id);


@Insert("INSERT INTO student(id, name, passport) VALUES (#{id}, #{name}, #{passport})")

public int insert(Student student);


@Update("Update student set name=#{name}, passport=#{passport} where id=#{id}")

public int update(Student student);

 

}


-> 이거 말고는 크게 없다. Hibernate 이거보다도 훨씬 편하게 개발할 수 있다고 주장한다.


2. GitHub - mybatis/spring-boot-starter: MyBatis integration with Spring Boot, https://github.com/mybatis/spring-boot-starter/, Accessed by 2020-09-30, Last Modified .

-> 공식 사이트에서 제공해주는 예제 가이드이니 참고하면 된다. 다 완벽하게 되어 있는 건 아니고, 프로그램 사용 방법이 적혀져 있다.

반응형
728x90
300x250

[Sun Sys - Java] 태스트도구 JUnit 5 - Eclipse(STS 4.4)에서 사용하는 방법


프로그래밍을 하면서 태스트 작업을 하기 마련인데 자바에서 태스트 환경도구를 사용하는 방법에 대해서 소개하려고 한다.

수업 등에서는 다뤄볼 일이 적은 부분일 수도 있다. 쉬우면서 어려운 부분이 태스트 도구라고 본다.


IDE: Spring-tool-suite-4-4.7.2.RELEASE (2020-09-08 기준 - 최신)

JAR: 

1. org.junit.jupiter.api_5.6.0.v20200203-2009.jar

2. org.junit.jupiter.engine_5.6.0.v20200203-2009.jar

3. org.junit.jupiter.migrationsupport_5.6.0.v20200203-2009.jar

4. org.junit.jupiter.params_5.6.0.v20200203-2009.jar

5. org.junit.platform.commons_1.6.0.v20200203-2009.jar

6. org.junit.platform.engine_1.6.0.v20200203-2009.jar

7. org.junit.platform.lanucher_1.6.0.v20200203-2009.jar

8. org.junit.platform.runner_1.6.0.v20200203-2009.jar

9. org.junit.platform.suite.api_1.6.0.v20200203-2009.jar

10. org.junit.vintage.engine_5.6.0.v20200203-2009.jar

11. org.opentest4j_1.2.0.v20190826-0900.jar

12. org.apiguardian_1.1.0.v20190826-0900.jar

13. org.junit_4.13.0.v20200204-1500.jar

14. org.hamcrest_1.2.0.v20180420-1519.jar


(EPL 라이선스 적용: 오픈소스)


* 공식 사용 메뉴얼: 사이트
https://junit.org/junit5/docs/current/user-guide/

* Assert 관련 API
http://junit.sourceforge.net/javadoc/org/junit/Assert.html




1. 사용 방법 - 영상


아주 간결하게 필요한 부분 위주로 소개하였으니 부담없이 시청해도 된다.



영상 1. Eclipse에서 프로젝트 생성하기 및 JUnit 셋팅하기



영상 2. JUnit 5 - 태스트 케이스 작성 및 동작 시키기




2. 사용 방법(2) - 프로젝트 생성하기


프로젝트를 생성하는 방법을 시작으로 소개하겠다.



그림 1. 프로젝트 생성하기


프로젝트 익스플로러(Project)에서 마우스 오른쪽 버튼을 클릭한다.

New-> Project를 클릭한다.



그림 2. 프로젝트 생성하기


Java Project를 클릭한다.

Next를 클릭한다.



그림 3. 프로젝트 생성하기


Project-name을 입력한 후 Finish를 누른다.



3. Properties - Junit 5 Class Path 등록하기 (Build Path 설정)


제일 중요한 작업이 아닐까 싶다.

이 셋팅을 안 해버리면, 사용할 수 없다. 물론 수동으로 등록하는 방법도 있겠으나 비효율적이다.



그림 4. 프로젝트 클릭 후 마우스 오른쪽 버튼 메뉴 모습


프로젝트를 클릭한다.

마우스 오른쪽 버튼을 클릭한 후, "Properties"를 클릭한다.



그림 5. 프로젝트 속성 - Java Build Path -> ClassPath 클릭 후 과정


Java Build Path를 클릭한다.

Libraries를 클릭한다.

ClassPath를 클릭한다.

Add Library를 클릭한다.



그림 6. Junit5 - 추가하기(1)


JUnit을 선택한다.

Next를 클릭한다.




그림 7. Junit5 - 추가하기(2)


Junit5를 선택한다.

Finish를 누른다.



그림 8. Junit5 - 추가 완료한 모습


다음처럼 등록되면 성공적으로 작업을 완료한 것이다.



4. Class 만들기


실제 태스트를 진행할 예를 하나 만들겠다.



그림 9. Class 만들기(1)


src 폴더를 클릭한 후 마우스 오른쪽 버튼으로 클릭한다.

New->Class를 클릭한다.



그림 10. Class 만들기(2)


Package는 적당히 입력해준다. (예: com.example)

Name을 Calculate라고 입력한다.

Finish를 누른다.



그림 11. Class 만들기(2)


코드를 작성해준다.


public int plus(int a, int b){

     return a + b;

}



5. Junit Test Case - 작성하기 


작성한 클래스를 태스트 케이스를 작성하여 태스트하도록 하겠다.


그림 12. Test Case 생성하기(1)


com.example 패키지를 마우스 오른쪽으로 클릭한다.

New->Other를 클릭한다.




그림 13. Test Case 생성하기(2)


Junit Test Case를 클릭한다.

Next를 누른다.



그림 14. Test Case 생성하기(3)


Class under test의 Browse를 클릭한다.



그림 15. Test Case 생성하기(2)


앞서 만든 "Calculate"를 검색한다.

Calculate를 선택한다.

OK를 누른다.



그림 16. Test Case 생성하기(3)


Package명을 입력한다.

Name을 입력한다.

Next를 누른다.



그림 17. Test Case 생성하기(4)


plus 함수를 선택한다.

Finish를 누른다.



6. Junit Test Case - 태스트 작업 실행하기 


태스트 명세를 완료하였다면, 태스트를 수행하도록 하겠다.



그림 18. Test Case 실행하기(1)


하나 예로 코드를 입력해준다.


@Test

void testPlus(){

      assertEquals(3, new Caculate().plus(2, 3));

}


이 코드는 직감적으로 plus 함수의 결과가 3이 되어야 참인데, 5라는 것을 코드만 보고도 알 수 있다.

외형 코드 말고 세부적인 코드에서 사람이 생각하는 결과를 원하는 게 아니라, 컴퓨터가 3으로 출력하는지 확인하는 것이다.



그림 19. Test Case 실행하기(2)


CalculateTest.java를 마우스 오른쪽 버튼으로 클릭한다.

Run As->JUnit Test를 클릭한다.



그림 20. Test Case 결과 (3)


결과값이 실패했다고 빨강색 진행바와 함수가 올라오는 것을 확인할 수 있다.

코드를 변경해서 시도해보자.


@Test

void testPlus(){

      assertEquals(5, new Caculate().plus(2, 3));

}


직감적으로 5가 되면 맞는 것이다.

진짜 5가 맞는지 확인해보자.


CalculateTest.java를 마우스 오른쪽 버튼으로 클릭한다.

Run as-> JUnit Test를 클릭한다.



그림 21. Test Case 결과 (4)


녹색 불이 들어오면서 이상이 없는 것을 살펴볼 수 있었다.



* JUnit Assert 주요 메서드와 사용 예시


 assert 메서드

설명 

 assertArrayEquals(a, b);

배열 a, b의 일치 여부

assertEquals(a, b);

객체 A와 B가 일치함을 확인.

assertSame(a, b);

 객체 A와 B가 같은 객체임을 확인한다.
assertEquals 메서드는 두 객체의 값이 같은지 검사를 한다.

assertSame메서드는 두 객체가 동일한가

즉, 하나의 객체여부를 확인한다. (== 연산자 역할)

assertTrue(a);

 조건 A가 참인가를 확인한다.

 assertNotNull(a);

객체 A가 null이 아님을 확인한다.

assertFalse(a);

조건 A가 거짓인지를 확인한다.



String empname[] = {"hwani","kimchi"};

String studentname[] = {"hama","sumi"};

assertArrayEquals(empname, studentname);


List someList = someClass.getSomeList();

assertNotNull("조회결과 null", someList);


assertTrue(someList.size() > 0);


int score = 5;

assertFalse( score < 0 ) ;


assertEquals(3, someList.size()); 



반응형

+ Recent posts