GWT-JUnit 통합
GWT는 JUnit 테스트 프레임 워크를 사용하여 클라이언트 측 코드의 자동화 된 테스트를위한 탁월한 지원을 제공합니다. 이 기사에서는 GWT 및 JUNIT 통합을 보여줍니다.
Junit 아카이브 다운로드
JUnit 공식 사이트 − https://www.junit.org
다운로드 Junit-4.10.jar
| OS | 아카이브 이름 | 
|---|---|
| 윈도우 | junit4.10.jar | 
| 리눅스 | junit4.10.jar | 
| 맥 | junit4.10.jar | 
다운로드 한 jar 파일을 컴퓨터의 특정 위치에 저장합니다. 우리는 그것을 저장했습니다C:/ > JUNIT
GWT 설치 폴더 찾기
| OS | GWT 설치 폴더 | 
|---|---|
| 윈도우 | 기음 : \ GWT \ gwt-2.1.0 | 
| 리눅스 | /usr/local/GWT/gwt-2.1.0 | 
| 맥 | / 라이브러리 /GWT/gwt-2.1.0 | 
GWTTestCase 클래스
GWT는 GWTTestCaseJUnit 통합을 제공하는 기본 클래스. JUnit에서 GWTTestCase를 확장하는 컴파일 된 클래스를 실행하면 테스트 실행 중에 애플리케이션 동작을 에뮬레이트하는 역할을하는 HtmlUnit 브라우저가 시작됩니다.
GWTTestCase는 JUnit의 TestCase에서 파생 된 클래스이며 JUnit TestRunner를 사용하여 실행할 수 있습니다.
webAppCreator 사용
GWT는 특별한 명령 줄 도구를 제공합니다. webAppCreator 이는 우리를 위해 시작 테스트 케이스를 생성 할 수 있으며, 개발 모드와 프로덕션 모드 모두에서 테스트하기위한 개미 대상 및 이클립스 실행 구성을 생성 할 수 있습니다.
명령 프롬프트를 열고 C:\ > GWT_WORKSPACE > 테스트 지원으로 새 프로젝트를 만들려는 위치에서 다음 명령을 실행합니다.
C:\GWT_WORKSPACE>C:\GWT\gwt-2.1.0\webAppCreator 
   -out HelloWorld 
   -junit C:\JUNIT\junit-4.10.jar 
   com.tutorialspoint.HelloWorld주목할 점
- webAppCreator 명령 줄 유틸리티를 실행하고 있습니다.
- HelloWorld는 생성 할 프로젝트의 이름입니다.
- -junit 옵션은 webAppCreator에 junit 지원을 프로젝트에 추가하도록 지시합니다.
- com.tutorialspoint.HelloWorld는 모듈의 이름입니다.
출력을 확인하십시오.
Created directory HelloWorld\src
Created directory HelloWorld\war
Created directory HelloWorld\war\WEB-INF
Created directory HelloWorld\war\WEB-INF\lib
Created directory HelloWorld\src\com\tutorialspoint
Created directory HelloWorld\src\com\tutorialspoint\client
Created directory HelloWorld\src\com\tutorialspoint\server
Created directory HelloWorld\src\com\tutorialspoint\shared
Created directory HelloWorld\test\com\tutorialspoint
Created directory HelloWorld\test\com\tutorialspoint\client
Created file HelloWorld\src\com\tutorialspoint\HelloWorld.gwt.xml
Created file HelloWorld\war\HelloWorld.html
Created file HelloWorld\war\HelloWorld.css
Created file HelloWorld\war\WEB-INF\web.xml
Created file HelloWorld\src\com\tutorialspoint\client\HelloWorld.java
Created file 
HelloWorld\src\com\tutorialspoint\client\GreetingService.java
Created file 
HelloWorld\src\com\tutorialspoint\client\GreetingServiceAsync.java
Created file 
HelloWorld\src\com\tutorialspoint\server\GreetingServiceImpl.java
Created file HelloWorld\src\com\tutorialspoint\shared\FieldVerifier.java
Created file HelloWorld\build.xml
Created file HelloWorld\README.txt
Created file HelloWorld\test\com\tutorialspoint\HelloWorldJUnit.gwt.xml
Created file HelloWorld\test\com\tutorialspoint\client\HelloWorldTest.java
Created file HelloWorld\.project
Created file HelloWorld\.classpath
Created file HelloWorld\HelloWorld.launch
Created file HelloWorld\HelloWorldTest-dev.launch
Created file HelloWorld\HelloWorldTest-prod.launch테스트 클래스 이해 : HelloWorldTest.java
package com.tutorialspoint.client;
import com.tutorialspoint.shared.FieldVerifier;
import com.google.gwt.core.client.GWT;
import com.google.gwt.junit.client.GWTTestCase;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.rpc.ServiceDefTarget;
/**
 * GWT JUnit tests must extend GWTTestCase.
 */
public class HelloWorldTest extends GWTTestCase {
   /**
    * must refer to a valid module that sources this class.
    */
   public String getModuleName() {
      return "com.tutorialspoint.HelloWorldJUnit";
   }
   /**
    * tests the FieldVerifier.
    */
   public void testFieldVerifier() {
      assertFalse(FieldVerifier.isValidName(null));
      assertFalse(FieldVerifier.isValidName(""));
      assertFalse(FieldVerifier.isValidName("a"));
      assertFalse(FieldVerifier.isValidName("ab"));
      assertFalse(FieldVerifier.isValidName("abc"));
      assertTrue(FieldVerifier.isValidName("abcd"));
   }
   /**
    * this test will send a request to the server using the greetServer
    *  method in GreetingService and verify the response.
    */
   public void testGreetingService() {
      /* create the service that we will test. */
      GreetingServiceAsync greetingService = 
      GWT.create(GreetingService.class);
      ServiceDefTarget target = (ServiceDefTarget) greetingService;
      target.setServiceEntryPoint(GWT.getModuleBaseURL() 
      + "helloworld/greet");
      /* since RPC calls are asynchronous, we will need to wait 
       for a response after this test method returns. This line 
       tells the test runner to wait up to 10 seconds 
       before timing out. */
      delayTestFinish(10000);
      /* send a request to the server. */
      greetingService.greetServer("GWT User", 
         new AsyncCallback<String>() {
         public void onFailure(Throwable caught) {
            /* The request resulted in an unexpected error. */
            fail("Request failure: " + caught.getMessage());
         }
         public void onSuccess(String result) {
            /* verify that the response is correct. */
            assertTrue(result.startsWith("Hello, GWT User!"));
            /* now that we have received a response, we need to 
             tell the test runner that the test is complete. 
             You must call finishTest() after an asynchronous test 
             finishes successfully, or the test will time out.*/
            finishTest();
         }
      });
   }
}주목할 점
| Sr. 아니. | 노트 | 
|---|---|
| 1 | HelloWorldTest 클래스는 HelloWorld / test 디렉토리 아래의 com.tutorialspoint.client 패키지에 생성되었습니다. | 
| 2 | HelloWorldTest 클래스에는 HelloWorld에 대한 단위 테스트 케이스가 포함됩니다. | 
| 삼 | HelloWorldTest 클래스는 com.google.gwt.junit.client 패키지의 GWTTestCase 클래스를 확장합니다. | 
| 4 | HelloWorldTest 클래스에는 GWT 모듈의 이름을 반환해야하는 추상 메서드 (getModuleName)가 있습니다. HelloWorld의 경우 com.tutorialspoint.HelloWorldJUnit입니다. | 
| 5 | HelloWorldTest 클래스는 두 개의 샘플 테스트 케이스 testFieldVerifier, testSimple로 생성됩니다. testGreetingService를 추가했습니다. | 
| 6 | 이러한 메소드는 GWTTestCase의 조상 인 JUnit Assert 클래스에서 상속하는 많은 assert * 함수 중 하나를 사용합니다. | 
| 7 | assertTrue (boolean) 함수는 전달 된 부울 인수가 true로 평가된다는 것을 주장합니다. 그렇지 않으면 JUnit에서 실행할 때 테스트가 실패합니다. | 
GWT-JUnit 통합 완료 예제
이 예제는 GWT에서 JUnit 통합의 예제를 보여주는 간단한 단계를 안내합니다.
위에서 만든 GWT 애플리케이션을 업데이트하려면 다음 단계를 따르세요.
| 단계 | 기술 | 
|---|---|
| 1 | 기존 프로젝트 가져 오기 마법사 (파일 → 가져 오기 → 일반 → 기존 프로젝트를 작업 공간으로)를 사용하여 Eclipse에서 HelloWorld 라는 이름으로 프로젝트 를 가져 오십시오. | 
| 2 | 아래 설명과 같이 HelloWorld.gwt.xml , HelloWorld.css , HelloWorld.html 및 HelloWorld.java 를 수정하십시오 . 나머지 파일은 변경하지 마십시오. | 
| 삼 | 애플리케이션을 컴파일하고 실행하여 구현 된 논리의 결과를 확인합니다. | 
다음은 Eclipse의 프로젝트 구조입니다.
 
                다음은 수정 된 모듈 설명 자의 내용입니다. src/com.tutorialspoint/HelloWorld.gwt.xml.
<?xml version = "1.0" encoding = "UTF-8"?>
<module rename-to = 'helloworld'>
   <!-- Inherit the core Web Toolkit stuff.                        -->
   <inherits name = 'com.google.gwt.user.User'/>
   <!-- Inherit the default GWT style sheet.                       -->
   <inherits name = 'com.google.gwt.user.theme.clean.Clean'/>
   <!-- Inherit the UiBinder module.                               -->
   <inherits name = "com.google.gwt.uibinder.UiBinder"/>
   <!-- Specify the app entry point class.                         -->
   <entry-point class = 'com.tutorialspoint.client.HelloWorld'/>
  
   <!-- Specify the paths for translatable code                    -->
   <source path = 'client'/>
   <source path = 'shared'/>
</module>다음은 수정 된 스타일 시트 파일의 내용입니다. war/HelloWorld.css.
body {
   text-align: center;
   font-family: verdana, sans-serif;
}
h1 {
   font-size: 2em;
   font-weight: bold;
   color: #777777;
   margin: 40px 0px 70px;
   text-align: center;
}다음은 수정 된 HTML 호스트 파일의 내용입니다. war/HelloWorld.html.
<html>
   <head>
      <title>Hello World</title>
      <link rel = "stylesheet" href = "HelloWorld.css"/>
      <script language = "javascript" src = "helloworld/helloworld.nocache.js">
      </script>
   </head>
   <body>
      <h1>JUnit Integration Demonstration</h1>
      <div id = "gwtContainer"></div>
   </body>
</html>HelloWorld.java의 내용을 src/com.tutorialspoint/client 다음과 함께 패키지
package com.tutorialspoint.client;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DecoratorPanel;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
public class HelloWorld implements EntryPoint {
	
   public void onModuleLoad() {
      /*create UI */
      final TextBox txtName = new TextBox(); 
      txtName.setWidth("200");
      txtName.addKeyUpHandler(new KeyUpHandler() {
         @Override
         public void onKeyUp(KeyUpEvent event) {
            if(event.getNativeKeyCode() == KeyCodes.KEY_ENTER){
               Window.alert(getGreeting(txtName.getValue()));
            }				
         }
      });
      Label lblName = new Label("Enter your name: ");
      Button buttonMessage = new Button("Click Me!");
      buttonMessage.addClickHandler(new ClickHandler() {			
         @Override
         public void onClick(ClickEvent event) {
            Window.alert(getGreeting(txtName.getValue()));
         }
      });
      HorizontalPanel hPanel = new HorizontalPanel();	
      hPanel.add(lblName);
      hPanel.add(txtName);
      hPanel.setCellWidth(lblName, "130");
      VerticalPanel vPanel = new VerticalPanel();
      vPanel.setSpacing(10);
      vPanel.add(hPanel);
      vPanel.add(buttonMessage);
      vPanel.setCellHorizontalAlignment(buttonMessage, 
      HasHorizontalAlignment.ALIGN_RIGHT);
      DecoratorPanel panel = new DecoratorPanel();
      panel.add(vPanel);
      // Add widgets to the root panel.
      RootPanel.get("gwtContainer").add(panel);
   }  
   
   public String getGreeting(String name){
      return "Hello "+name+"!";
   }
}HelloWorldTest.java의 내용을 test/com.tutorialspoint/client 다음과 함께 패키지
package com.tutorialspoint.client;
import com.tutorialspoint.shared.FieldVerifier;
import com.google.gwt.core.client.GWT;
import com.google.gwt.junit.client.GWTTestCase;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.rpc.ServiceDefTarget;
/**
 * GWT JUnit tests must extend GWTTestCase.
 */
public class HelloWorldTest extends GWTTestCase {
   /**
    * must refer to a valid module that sources this class.
    */
   public String getModuleName() {
      return "com.tutorialspoint.HelloWorldJUnit";
   }
   /**
    * tests the FieldVerifier.
    */
   public void testFieldVerifier() {
      assertFalse(FieldVerifier.isValidName(null));
      assertFalse(FieldVerifier.isValidName(""));
      assertFalse(FieldVerifier.isValidName("a"));
      assertFalse(FieldVerifier.isValidName("ab"));
      assertFalse(FieldVerifier.isValidName("abc"));
      assertTrue(FieldVerifier.isValidName("abcd"));
   }
   /**
      * this test will send a request to the server using the greetServer
      *  method in GreetingService and verify the response.
   */
   public void testGreetingService() {
      /* create the service that we will test. */
      GreetingServiceAsync greetingService = 
      GWT.create(GreetingService.class);
      ServiceDefTarget target = (ServiceDefTarget) greetingService;
      target.setServiceEntryPoint(GWT.getModuleBaseURL() 
      + "helloworld/greet");
      /* since RPC calls are asynchronous, we will need to wait 
       for a response after this test method returns. This line 
       tells the test runner to wait up to 10 seconds 
       before timing out. */
      delayTestFinish(10000);
      /* send a request to the server. */
      greetingService.greetServer("GWT User", 
         new AsyncCallback<String>() {
         public void onFailure(Throwable caught) {
            /* The request resulted in an unexpected error. */
            fail("Request failure: " + caught.getMessage());
         }
         public void onSuccess(String result) {
            /* verify that the response is correct. */
            assertTrue(result.startsWith("Hello, GWT User!"));
            /* now that we have received a response, we need to 
             tell the test runner that the test is complete. 
             You must call finishTest() after an asynchronous test 
             finishes successfully, or the test will time out.*/
            finishTest();
         }
      });
	
      /**
         * tests the getGreeting method.
      */
      public void testGetGreeting() {
         HelloWorld helloWorld = new HelloWorld();
         String name = "Robert";
         String expectedGreeting = "Hello "+name+"!";
         assertEquals(expectedGreeting,helloWorld.getGreeting(name));
      }
   }
}생성 된 실행 구성을 사용하여 Eclipse에서 테스트 케이스 실행
개발 모드와 프로덕션 모드 모두에 대해 webAppCreator에서 생성 한 시작 구성을 사용하여 Eclipse에서 단위 테스트를 실행합니다.
개발 모드에서 JUnit 테스트 실행
- Eclipse 메뉴 표시 줄에서 실행 → 구성 실행 ...을 선택하십시오.
- JUnit 섹션에서 HelloWorldTest-dev를 선택하십시오.
- 인수에 변경 사항을 저장하려면 적용을 누르십시오.
- 테스트를 실행하려면 실행을 누릅니다.
응용 프로그램에 문제가 없으면 다음과 같은 결과가 생성됩니다.
 
                프로덕션 모드에서 JUnit 테스트 실행
- Eclipse 메뉴 표시 줄에서 실행 → 구성 실행 ...을 선택하십시오.
- JUnit 섹션에서 HelloWorldTest-prod를 선택하십시오.
- 인수에 변경 사항을 저장하려면 적용을 누르십시오.
- 테스트를 실행하려면 실행을 누릅니다.
응용 프로그램에 문제가 없으면 다음과 같은 결과가 생성됩니다.
