반응형

 

 

 

 

 

Maven으로 Java프로젝트 만들기

 

 

 

 

pom.xml 파일에 JDK를 사용하기 위한 플러그인 설정을 추가합니다.

<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>kr.or.connect</groupId>
  <artifactId>diexam01</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>diexam01</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
  
-------------------------------------추가----------------------------------------------------
  <build>
     <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.6.1</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>
    </plugins>
  </build>
----------------------------------------------------------------------------------------------

</project>

 

: 전 이미 maven-compiler-plugin 이 이미 있기 때문에 버전만 1.7에서 1.8로 변경하였습니다.

 

 

프로젝트를 선택하고, Maven -> Update Project를 선택합니다.

위와 같은 창이 뜨면 OK버튼을 클릭합니다.

 

 


실습코드

App.java

package kr.or.connect.diexam01;

/**
 * Hello world!
 *
 */
public class App 
{
    public static void main( String[] args )
    {
        System.out.println( "Hello World!" );
    }
}

 

AppTest.java

package kr.or.connect.diexam01;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

/**
 * Unit test for simple App.
 */
public class AppTest 
    extends TestCase
{
    /**
     * Create the test case
     *
     * @param testName name of the test case
     */
    public AppTest( String testName )
    {
        super( testName );
    }

    /**
     * @return the suite of tests being tested
     */
    public static Test suite()
    {
        return new TestSuite( AppTest.class );
    }

    /**
     * Rigourous Test :-)
     */
    public void testApp()
    {
        assertTrue( true );
    }
}

 

 

AppTest.java 를 선택한 후 우측버튼을 클릭하고 Run As -> JUnit Test 메뉴를 선택합니다.

하단의 JUnit 뷰에 하나의 테스트가 성공했다는 메시지와 함께 녹색 막대가 보여집니다.

Bean class란?

예전에는 Visual 한 컴포넌트를 Bean이라고 불렀지만, 근래 들어서는 일반적인 Java클래스를 Bean클래스라고 보통 말합니다.

Bean클래스의 3가지 특징은 다음과 같습니다.

  • 기본생성자를 가지고 있습니다.
  • 필드는 private하게 선언합니다.
  • getter, setter 메소드를 가집니다.
  • getName() setName() 메소드를 name 프로퍼티(property)라고 합니다. (용어 중요)

 

 


실습코드

UserBean.java

package kr.or.connect.diexam01;

//빈클래스
public class UserBean {
	
	//필드는 private한다.
	private String name;
	private int age;
	private boolean male;
	
	//기본생성자를 반드시 가지고 있어야 한다.
	public UserBean() {
	}
	
	public UserBean(String name, int age, boolean male) {
		this.name = name;
		this.age = age;
		this.male = male;
	}

	// setter, getter메소드는 프로퍼티라고 한다.
	public void setName(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public boolean isMale() {
		return male;
	}

	public void setMale(boolean male) {
		this.male = male;
	}

}

 

Spring Bean Factory를 이용하여 Bean객체 이용하기

1) pom.xml 파일을 다음과 같이 수정합니다.

<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>kr.or.connect</groupId>
  <artifactId>diexam01</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>diexam01</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <spring.version> 4.3.14.RELEASE</spring.version>
  </properties>

  <dependencies>
	<!-- Spring -->
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-context</artifactId>
		<version>${spring.version}</version>
	</dependency>
  
  
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
  
  <build>
     <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.6.1</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>
    </plugins>
  </build>
</project>

 

2) 추가된 라이브러리 확인합니다.

 

3) resources 소스 폴더를 생성합니다.

프로젝트를 선택하고, 오른쪽 버튼을 클릭한 후 New -> Folder를 선택합니다.

src/main 폴더를 선택한 후 forder name에 resources라고 Finish버튼을 클릭합니다.

 

해당 폴더를 선택하고, 우측버튼을 클릭하여 New – File을 선택합니다. src/main/resources 폴더를 선택한 후 File name에 applicationContext.xml 을 입력하고 Finish버튼을 클릭합니다.

위와 같이 생성되었으면 더블클릭하여 파일을 엽니다.

4) resources 소스 폴더에 xml 파일을 작성합니다.

 

 


실습코드 

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

	<bean id="userBean" class="kr.or.connect.diexam01.UserBean"></bean>

</beans>

bean 태그를 하나 입력했는데, 위의 태그는 다음과 같은 의미를 가집니다.

UserBean userBean - new UserBean();

 

ApplicationContext를 이용해서 설정파일을 읽어들여 실행하기

ApplicationContextExam01

package kr.or.connect.diexam01;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class ApplicationContextExam01 {

	public static void main(String[] args) {
		ApplicationContext ac = new ClassPathXmlApplicationContext( 
				"classpath:applicationContext.xml"); 
		System.out.println("초기화 완료.");
		
		UserBean userBean = (UserBean)ac.getBean("userBean");
		userBean.setName("kim");
		System.out.println(userBean.getName());
		
		UserBean userBean2 = (UserBean)ac.getBean("userBean");
		if(userBean == userBean2) {
			System.out.println("같은 인스턴스이다.");
		}
		
	}
}
반응형
반응형

 

 

 

컨테이너(Container)

컨테이너는 인스턴스의 생명주기를 관리하며, 생성된 인스턴스에게 추가적인 기능을 제공합니다.

예를 들어, Servlet을 실행해주는 WAS는 Servlet 컨테이너를 가지고 있다고 말합니다.

WAS는 웹 브라우저로부터 서블릿 URL에 해당하는 요청을 받으면, 서블릿을 메모리에 올린 후 실행합니다.

개발자가 서블릿 클래스를 작성했지만, 실제로 메모리에 올리고 실행하는 것은 WAS가 가지고 있는 Servlet 컨테이너입니다.

Servlet컨테이너는 동일한 서블릿에 해당하는 요청을 받으면, 또 메모리에 올리지 않고 기존에 메모리에 올라간 서블릿을 실행하여 그 결과를 웹 브라우저에게 전달합니다.

컨테이너는 보통 인스턴스의 생명주기를 관리하며, 생성된 인스턴스들에게 추가적인 기능을 제공하는 것을 말합니다.

 

IoC(Inversion of Control) 

컨테이너가 코드 대신 오브젝트의 제어권을 갖고 있어 IoC(제어의 역전)이라 합니다.

예를 들어, 서블릿 클래스는 개발자가 만들지만, 그 서블릿의 메소드를 알맞게 호출하는 것은 WAS입니다.

이렇게 개발자가 만든 어떤 클래스나 메소드를 다른 프로그램이 대신 실행해주는 것을 제어의 역전이라고 합니다.

 

DI(Dependency Injection)

DI는 의존성 주입이란 뜻을 가지고 있으며, 클래스 사이의 의존 관계를 빈(Bean) 설정 정보를 바탕으로 컨테이너가 자동으로 연결해주는 것을 말합니다.

 

DI가 적용 안 된 예

개발자가 직접 인스턴스를 생성합니다.

class 엔진 {

}

class 자동차 {
     엔진 v5 = new 엔진();
}

 

 

 

Spring에서 DI가 적용된 예

엔진 type의 v5변수에 아직 인스턴스가 할당되지 않았습니다.

컨테이너가 v5변수에 인스턴스를 할당해주게 됩니다.

@Component
class 엔진 {

}

@Component
class 자동차 {
     @Autowired
     엔진 v5;
}

 

 

 

 

Spring에서 제공하는 IoC/DI 컨테이너

  • BeanFactory : IoC/DI에 대한 기본 기능을 가지고 있습니다.
  • ApplicationContext : BeanFactory의 모든 기능을 포함하며, 일반적으로 BeanFactory보다 추천됩니다. 트랜잭션처리, AOP등에 대한 처리를 할 수 있습니다. BeanPostProcessor, BeanFactoryPostProcessor등을 자동으로 등록하고, 국제화 처리, 어플리케이션 이벤트 등을 처리할 수 습니다.
  • BeanPostProcessor : 컨테이너의 기본로직을 오버라이딩하여 인스턴스화 와 의존성 처리 로직 등을 개발자가 원하는 대로 구현 할 수 있도록 합니다.
  • BeanFactoryPostProcessor : 설정된 메타 데이터를 커스터마이징 할 수 있습니다.
반응형
반응형
반응형
반응형

 

 

 

 

 

 

 

We will gonna execute project in Eclipse.

1. new > maven project > maven-archetype-webapp > enter an artifact id > finish

 

2. changing java version in pom.xml

1.7 -> 1.8

 <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
  </properties>

 

 

 

3. add servlet dependency at pom.xml

<dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
        <scope>provided</scope>
    </dependency>
    
     <dependency>
		<groupId>mysql</groupId>
		<artifactId>mysql-connector-java</artifactId>
		<version>5.1.45</version>
	</dependency>

And don't forget to click [ maven > Update Project ] to adapt the settings.

Restart Eclipse.

 

 

 

4. Editing Web.xml

 

Open Navigator

src > main > webapp > WEB-INF > web.xml

 

change from

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
</web-app>

to

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">
  <display-name>Archetype Created Web Application</display-name>
</web-app>

 

 

 

 

5. Change web module version

 

open navigator

.settings/org.eclipse.wst.common.project.facet.core.xml

 

You can see like this in xml file

<?xml version="1.0" encoding="UTF-8"?>
<faceted-project>
  <fixed facet="wst.jsdt.web"/>
  <installed facet="jst.web" version="2.3"/>
  <installed facet="wst.jsdt.web" version="1.0"/>
  <installed facet="java" version="1.8"/>
</faceted-project>

 

change version from "2.3" to "3.1"

<?xml version="1.0" encoding="UTF-8"?>
<faceted-project>
  <fixed facet="wst.jsdt.web"/>
  <installed facet="jst.web" version="3.1"/>
  <installed facet="wst.jsdt.web" version="1.0"/>
  <installed facet="java" version="1.8"/>
</faceted-project>

 

 

 

 

 

 

 

 

 

6. Make src/main/java 

 

src > main > [ make java file ]

And there will be src/main/java

 

and make package which names like 'kr.or.connect.blahblah'

 

 

 

 

So, our Maven Setting is all end

 

 

반응형
반응형

 

 

 

 

 

 

 

1. Spring Framework란?

 

  • 엔터프라이즈급 어플리케이션을 구축할 수 있는 가벼운 솔루션이자, 원스-스탑-숍(One-Stop-Shop)
  • 원하는 부분만 가져다 사용할 수 있도록 모듈화가 잘 되어 있습니다.
  • IoC 컨테이너입니다.
  • 선언적으로 트랜잭션을 관리할 수 있습니다.
  • 완전한 기능을 갖춘 MVC Framework를 제공합니다.
  • AOP 지원합니다.
  • 스프링은 도메인 논리 코드와 쉽게 분리될 수 있는 구조로 되어 있습니다.

 

 

 

 

 

 

 

2. 프레임 워크 모듈

  • 스프링 프레임워크는 약 20개의 모듈로 구성되어 있습니다.
  • 필요한 모듈만 가져다 사용할 수 있습니다.

 

 

 

3. AOP 와 인스트루멘테이션 (Instrumentation)

  • spring-AOP : AOP 얼라이언스(Alliance)와 호환되는 방법으로 AOP를 지원합니다.
  • spring-aspects : AspectJ와의 통합을 제공합니다.
  • spring-instrument : 인스트루멘테이션을 지원하는 클래스와 특정 WAS에서 사용하는 클래스로 더 구현체를 제공합니다. 참고로 BCI(Byte Code Instrumentations)은 런타임이나 로드(Load) 때 클래스의 바이트 코드에 변경을 가하는 방법을 말합니다.

 

 

 

 

 

4. 메시징(Messaging)

  • spring-messaging : 스프링 프레임워크 4는 메시지 기반 어플리케이션을 작성할 수 있는 Message, MessageChannel, MessageHandler 등을 제공합니다. 또한, 해당 모듈에는 메소드에 메시지를 맵핑하기 위한 어노테이션도 포함되어 있으며, Spring MVC 어노테이션과 유사합니다.

 

 

 

5. 데이터 엑서스(Data Access) / 통합(Integration)

  • 데이터 엑세스/통합 계층은 JDBC, ORM, OXM, JMS 및 트랜잭션 모듈로 구성되어 있다.
  • spring-jdbc : 자바 JDBC프로그래밍을 쉽게 할 수 있도록 기능을 제공합니다.
  • spring-tx : 선언적 트랜잭션 관리를 할 수 있는 기능을 제공합니다.
  • spring-orm : JPA, JDO및 Hibernate를 포함한 ORM API를 위한 통합 레이어를 제공합니다.
  • spring-oxm : JAXB, Castor, XMLBeans, JiBX 및 XStream과 같은 Object/XML 맵핑을 지원합니다.
  • spring-jms : 메시지 생성(producing) 및 사용(consuming)을 위한 기능을 제공, Spring Framework 4.1부터 spring-messaging모듈과의 통합을 제공합니다.

 

 

6. 웹(Web)

  • 웹 계층은 spring-web, spring-webmvc, spring-websocket, spring-webmvc-portlet 모듈로 구성됩니다.
  • spring-web : 멀티 파트 파일 업로드, 서블릿 리스너 등 웹 지향 통합 기능을 제공한다. HTTP클라이언트와 Spring의 원격 지원을 위한 웹 관련 부분을 제공합니다.
  • spring-webmvc : Web-Servlet 모듈이라고도 불리며, Spring MVC 및 REST 웹 서비스 구현을 포함합니다.
  • spring-websocket : 웹 소켓을 지원합니다.
  • spring-webmvc-portlet : 포틀릿 환경에서 사용할 MVC 구현을 제공합니다.

 

 

Q. 프레임워크와 라이브러리의 차이는 무엇일까?

A. 프레임워크는 골격이 아닐까 싶습니다. 프레임워크라는 골격을 기반으로 우리가 원하는대로 살을 붙여 제품을 만드는 것입니다. 그리고 그 살을 붙일 때 효과적으로 붙일 수 있도록 도와주는 도구가 라이브러리라고 생각합니다.

 

 

 

 

1. Spring Framework란?

- A lightweight solution for deploying enterprise-class applications, one-stop-shop
- It is well modularized so that you can use only the parts you want.
- This is an IoC container.
- You can manage transactions declaratively.
- Provides a fully functional MVC framework.
- AOP is supported.
- The spring has a structure that can be easily separated from the domain logic code.

 

 

 

2. Framework Module

The spring framework consists of approximately 20 modules.
Only the modules you need can be imported and used.


3. AOP Instrumentation

spring-AOP : supports AOP in a way that is compatible with the AOP Alliance.
spring-spect : provides integration with AspectJ.
spring-instrument : Provides more implementation into classes that support instrumentation and classes used by certain WASs. Note that Byte Code Instrumentation (BCI) refers to how to change the class' byte code at runtime or load.

 

 

 

 

4. Messaging

Spring-messaging: Spring Framework 4 provides messages, message channels, message handlers, and more to create message-based applications. The module also contains an annotation for mapping messages to the method, similar to Spring MVC annotation.



5. Data Access / Integration

The data access/integration layer consists of JDBC, ORM, OXM, JMS, and transaction modules.
spring-jdbc : Provides functionality to facilitate Java JDBC programming.
spring-tx : Provides the ability to manage declarative transactions.
spring-orm : Provides an integrated layer for ORM API including JPA, JDO, and Hibernate.
spring-oxm : JAXB, Castor, XMLBeans, JiBX 및 XStream과 같은 Object/XML 맵핑을 지원합니다.
Spring-jms: Provides functionality for generating and using messages and provides integration with spring-messaging modules from Spring Framework 4.1.

 

 

 

 

 

6. Web (Web)
- Web layer is consist of spring-web, spring-webmvc, spring-websocket, spring-webmvc-portlet modules.
- Spring-web: It provides web-oriented integration functions such as multi-part file upload and servlet listener. Provides Web-- - related parts for remote support for HTTP clients and Spring.
- spring-webmvc : also known as Web-Servlet Module, includes Spring MVC and REST Web Service implementations.
- spring-websocket : supports web sockets.
- spring-webmvc-portlet : Provides MVC implementation for use in portlet environment.

 

 

 

Q. What is the diffrence between framework and library ?

A. I think the framework is a skeleton. Based on the framework, we make the products as we want. And libraries are the tools that we use at that time.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

반응형
반응형

@SpringBootTest는 @SpringBootApplication 부터 시작하는 모든 빈을 스캔하고 등록해준다.

 

 

1. 시작은 spring-boot-starter-test 의존성 추가하는 것부터!

저는 스프링 이니셜라이져로 생성해서 자동으로 추가되었습니다.

<dependency>
	<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>

pom.xml

 

 

 

2. main 코드

package com.example.springboottest.sample;

import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SampleController {

    @Autowired
    private SampleService sampleService;

    @GetMapping("/hello")
    public String hello(){
        return "hello" + sampleService.getName();
    }
}

SampleController.java

 

 

@Service
public class SampleService {
    public String getName() {
        return "naeun";
    }
}

SampleService.java

 

 

 

3. @SpringBootTest

  • @RunWith(SpringRunner.class)랑 같이 써야 함.
  • 빈 설정 파일은 설정을 안해주나? 알아서 찾습니다. (@SpringBootApplication)

 

4. webEnvironment

  • MOCK: mock servlet environment. 내장 톰캣 구동 안 함.
  • RANDON_PORT, DEFINED_PORT: 내장 톰캣 사용 함.
  • NONE: 서블릿 환경 제공 안 함.

 

 

 

 

여기서 잠깐! Mock란?

실제 객체를 만들기엔 비용과 시간이 많이 들거나 의존성이 길게 걸쳐져 있어 제대로 구현하기 어려울 경우, 가짜 객체를 만들어 사용하는데, 이를 Mocking 이라고 한다.

 

여기서 잠깐! Dispatcher-Servlet이란?

Servlet Container에서 HTTP프로토콜을 통해 들어오는 모든 요청을 프레젠테이션 계층의 제일앞에 둬서 중앙집중식으로 처리해주는 프론트 컨트롤러(Front Controller)이다. 클라이언트로부터 어떠한 요청이 오면 Tomcat(톰캣)과 같은 서블릿컨테이너가 요청을 받는데, 이때 제일 앞에서 서버로 들어오는 모든 요청을 처리하는 *프론트 컨트롤러를 Spring에서 정의하였고, 이를 Dispatcher-Servlet이라고 합니다. 

 

여기서 잠깐! Front Controller란?

Front Controller는 주로 서블릿 컨테이너의 제일 앞에서 서버로 들어오는 클라이언트의 모든 요청을 받아서

처리해주는 컨트롤러인데, MVC 구조에서 함께 사용되는 패턴이다.

 

여기서 잠깐! @Autowired란?

이 어노테이션을 부여하면 각 상황의 타입에 맞는 IoC컨테이너 안에 존재하는 빈을 자동으로 주입해준다.

 

 

 

 

1) WebEnvironment 가 MOCK 일 때,

MockMVC 라는 클라이언트를 사용하려면

 

-> mockup이 된 서블릿과 인터렉션 하려면 MockMVC라는 클라이언트가 필요하다.

@AutoConfigureMockMvc : 어노테이션 추가

@Autowired
MockMvc mockMvc; : 본문에 추가

 

package com.example.springboottest.sample;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import static org.junit.jupiter.api.Assertions.*;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK)
@AutoConfigureMockMvc
public class SampleServiceTest {

    @Autowired
    MockMvc mockMvc;

    @Test
    public void hello() throws Exception {
        mockMvc.perform(get("/hello"))
                .andExpect(status().isOk())
                .andExpect(content().string("hellonaeun"))
                .andDo(print());
    }
}

SampleControllerTest.java

 

 

이렇게 하고 hello를 run하면 ! 에러가 뜬다...

junit 버전이 12이상 필요하다고 해서 12로 고쳐주었더니 잘 작동된다.

 

-> 여러가지 정보들을 보여준다.

 

 

 

 

 

2) WebEnvironment 가 RANDOM_PORT 일 때, (내장 톰캣이 뜸)

test용 restTemplate나 test용 client를 사용해야 한다. 

 

먼저 restTemplate을 사용해보자.

테스트할 때마다 Service단위로 가져오는게 부담스럽기 때문에 가짜 객체를 만들어준다.

-> @MockBean

  • ApplicationContext에 들어있는 빈을 Mock으로 만든 객체로 교체 함.
  • 모든 @Test 마다 자동으로 리셋.
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class SampleControllerTest {

    @Autowired
    TestRestTemplate testRestTemplate;

    @MockBean
    SampleService mockSampleService;

    @Test
    public void hello() throws Exception {
        when(mockSampleService.getName()).thenReturn("whiteship");

        String result = testRestTemplate.getForObject("/hello",String.class);
        assertThat(result).isEqualTo("hellowhiteship");

    }
}

SampleControllerTest.java

 

둘 다 whiteship으로 변경하여 테스트해보니 정상적으로 작동한다.

 

 

 

 

다음으로 webTestClient를 사용해보자.

webTestClient 는 RestTemplate과 다르게 비동기 방식이다.

 

 

webflux 의존성 추가해준다.

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>

 

 

test용 client 사용을 위해 restTemplate 대신,

@Autowired
WebTestClient webTestClient; 을 추가해준다.

package com.example.test2.sample;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.reactive.server.WebTestClient;
import org.springframework.test.web.servlet.MockMvc;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class SampleControllerTest {

    @Autowired
    WebTestClient webTestClient;

    @MockBean
    SampleService mockSampleService;

    @Test
    public void hello() throws Exception {
        when(mockSampleService.getName()).thenReturn("whiteship");

        webTestClient.get().uri("/hello").exchange()
                .expectStatus().isOk()
                .expectBody(String.class).isEqualTo("hellowhiteship");

    }
}

SampleControllerTest.java

 

 

 

 

 

 

 

슬라이스 테스트

  • 레이어 별로 잘라서 테스트하고 싶을 때
  • @JsonTest
  • @WebMvcTest
  • @WebFluxTest
  • @DataJpaTest
  • ...
반응형

+ Recent posts