개키우는개발자 : )

DI 애플리케이션 작성(2) 본문

JAVA/Spring Framework

DI 애플리케이션 작성(2)

DOGvelopers 2019. 2. 6. 17:28
반응형

Spring Framework DI 애플리케이션 작성(2)



학습 목표


  • JUnit의 개요와 특징
  • JUnit을 사용한 DI테스트 클래스
  • Spring-Test를 사용한 DI테스트 클래스


프로젝트 파일 목록프로젝트 파일 목록



1.JUnit 의 개요와 특징


1-1 JUnit의 특징


- TDD의 창시자인 Kent Beck과 디자인 패턴 책의 저자인 Erich Gamma가 작성했다.


- 단정(assert) 메서드로 테스트 케이스의 수행 결과를 판별한다.

예) assertEquals(예상 값, 실제 값)


- JUnit4 부터는 테스트를 지원하는 어노테이션을 제공한다.

@Test @Before @After


- 각 @Test 메서드가 호출할 때 마다 새로운 인스턴스를 생성하여 독립적인 테스트가 이루어지도록 한다.



2.JUnit을 사용한 DI 테스트 클래스


2-1 JUnit 라이브러리 설치


- https://mvnrepository.com/  -> junit 검색 ( https://mvnrepository.com/artifact/junit/junit

-> jUnit 4.12 버전을 pom.xml 에 추가


1
2
3
4
5
6
7
8
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
</dependency>
 
cs


2-2 JUnit에서 테스트를 지원하는 어노테이션(Annotaion)


- @Test

- @Test가 선언된 메서드는 테스트를 수행하는 메소드가 된다.

- JUnit은 각각의 테스트가 서로 영향을 주지 않고 독립적으로 실행됨을 원칙으로 하므로 @Test 마다 객체를 생성한다.


- @Ignore

- @Ignore가 선언된 메서드는 테스트를 실행하지 않게 한다.


- @Before

- @Before가 선언된 메서드는 @Test 메소드가 실행되기 전에 반드시 실행되어 진다.

- @Test 메소드에서 공통으로 사용하는 코드를 @Before 메소드에 선언하여 사용하면 된다.


- @After

- @After가 선언된 메서드는 @Test 메소드가 실행된 후 실행된다.


- @BeforeClass

- @BeforeClass 어노테이션은 @Test 메소드 보다 먼저 한번만 수행되어야 할 경우에 사용하면 된다.


- @AfterClass

- @AfterClass 어노테이션은 @Test 메소드 보다 나중에 한번만수행되어야 할 경우에 사용하면 된다.


JUnit에서 테스트를 지원하는 어노테이션(Annotaion)JUnit에서 테스트를 지원하는 어노테이션(Annotaion)



2-3 테스트 결과를 확인하는 단정(assert) 메서드


- assertEquals(a,b); : 객체 A와 B가 일치함을 확인한다.


- assertArrayEquals(a,b); : 배열 A와 B가 일치함을 확인한다.


- assertSame(a,b); : 객체 A와 B가 같은 객체임을 확인한다. assertEquals 메서드는 두 객체의 값이 같은지 확인하고, assertSame메서드는 두 객체의 레퍼런스가 동일한가를 확인한다.(==연산자)


- assertTrue(a); : 조건 A가 참인가를 확인한다.


- assertNotNull(a); : 객체 A가 null이 아님을 확인한다.


* 이외에도 다양한 assert 메서드가 존재함.

http://junit.sourceforge.net/javadoc/org/junit/Assert.html



2-4 JUnit을 사용한 DI 테스트 클래스(HelloBeanJunitTest.java) 작성


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package myspring.di.xml.test;
 
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
 
 
import myspring.di.xml.Hello;
import myspring.di.xml.Printer;
import static org.junit.Assert.*;
 
public class HelloBeanJunitTest {
 
    private ApplicationContext context;
    
    @Before
    public void init() {
        //IoC 컨테이너 생성
        //1.ApplicationContext 객체 생성
        context = new GenericXmlApplicationContext("config/beans.xml");
    }
    
    @Test
    public void test1(){
        
        //2. getBean() 호출
        Hello hello = (Hello) context.getBean("hello");
    
        //3. Hello 의 sayHello()호출.
        /*Assert.assertEquals("Hello Spring Study",hello.sayHellow());*/
        assertEquals("Hello Spring Study",hello.sayHellow());
        System.out.println(hello.sayHellow());
        //4. Hello 의 print() 호출
        hello.print();
        
        //5. SpringPrinter getBean() 호출
        Printer printer = context.getBean("printer",Printer.class);
        assertEquals("Hello Spring Study",printer.toString());
        System.out.println(printer.toString());
    }
    
    @Test
    public void test2(){
        
        Hello hello = (Hello) context.getBean("hello");
        
        Hello hello2 = (Hello) context.getBean("hello");
        
        assertSame(hello, hello2);
    }
}
 
cs


Ctrl + F11 (run as -> JUnit Test) 실행


1
2
Hello Spring Study
Hello Spring Study
cs


모든 테스트가 성공시 


테스트 성공테스트 성공


테스트 실패시 어떤 메서드가 오류가 났고 오류내용을 보여줍니다.


테스트 실패테스트 실패




3.Spring-Test를 사용한 DI 테스트 클래스



3-1 Spring-Test 라이브러리 설치


https://mvnrepository.com/  -> Spring-Test 검색 ( https://mvnrepository.com/artifact/org.springframework/spring-test/3.2.17.RELEASE ) 

-> jUnit 4.12 버전을 pom.xml 에 추가


1
2
3
4
5
6
7
8
<!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>3.2.17.RELEASE</version>
    <scope>test</scope>
</dependency>
 
cs


3-2 Spring-Test에서 테스트를 지원하는 어노테이션(Annotation)


@RunWith(SpringJUnit4ClassRunner.class)

- @RunWith는 JUnit 프레임워크의 테스트 실행방법을 확장할 때 사용하는 어노테이션이다.

- SpringJUnit4ClassRunner라는 클래스를 지정해주면 JUnit이 테스트를 진행하는 중에 

ApplicationContext를 만들고 관리하는 작업을 진행해 준다.

- RunWith 어노테이션은 각각의 테스트 별로 객체가 생성되더라도 싱글톤(Singleton)의 

ApplicationContext를 보장한다.


@ContextConfiguration

- 스프링 빈(Bean) 설정 파일의 위치를 지정할 때 사용되는 어노테이션이다.


@Autowired

- 스프링DI에서 사용되는 특별한 어노테이션이다.

- 해당 변수에 자동으로 빈(Bean)을 매핑 해준다.

- 스프링 빈(Bean) 설정 파일을 읽기 위해 굳이 GenericXmlApplicationContext를 사용할 필요가 없다.


3-3 Spring-Test를 사용한 DI 테스트 클래스(HelloBeanSpringTest.java)작성


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package myspring.di.xml.test;
 
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
 
import myspring.di.xml.Hello;
import myspring.di.xml.Printer;
import static org.junit.Assert.*;
 
import java.util.List;
 
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:config/beans.xml")
public class HelloBeanJunitSpringTest {
 
    @Autowired
    private ApplicationContext context;
 
    @Test
    public void test1() {
        // 2. getBean() 호출
        Hello hello = (Hello) context.getBean("hello");
 
        // 3. Hello 의 sayHello()호출.
        /* Assert.assertEquals("Hello Spring Study",hello.sayHellow()); */
        assertEquals("Hello Spring Study", hello.sayHellow());
        // 4. Hello 의 print() 호출
        hello.print();
 
        // 5. SpringPrinter getBean() 호출
        Printer printer = context.getBean("printer", Printer.class);
        assertEquals("Hello Spring Study", printer.toString());
 
    }
 
    @Test
    public void test2() {
 
        Hello hello = (Hello) context.getBean("hello");
 
        Hello hello1 = (Hello) context.getBean("hello");
 
        assertSame(hello, hello1);
    }
    
    @Test
@Ignore
    public void test3() {
        Hello hello = context.getBean("hello3",Hello.class);
        List<String> list = hello.getNames();
        for (String value: list) {
            System.out.println(value);
        }
 
    }
}
 
cs



실행하시면 테스트가 성공 하는걸볼 수 있습니다.


테스트 완벽 성공Test success



이상으로 DI 애플리케이션 Test 에 대해 알아보았습니다.


완성된 프로젝트 코드를 다운받으실수 있습니다.

https://dog-developers.tistory.com/30

반응형

'JAVA > Spring Framework' 카테고리의 다른 글

DI 애플리케이션 작성(4)  (0) 2019.02.07
DI 애플리케이션 작성(3)  (0) 2019.02.07
DI 애플리케이션 작성(1)  (0) 2019.02.06
IoC 컨테이너와 DI(Dependency Injection)  (2) 2019.02.06
프로젝트 시작하기  (0) 2019.01.30
Comments