Пример тестирования вызова RPC с использованием GWT-TestCase с GAE - PullRequest
2 голосов
/ 10 июня 2009

Как это для многих сокращений!

У меня проблемы с тестированием механизма RPC GWT с использованием GWT GWTTestCase. Я создал класс для тестирования с помощью инструмента junitCreator, включенного в GWT. Я пытаюсь выполнить тестирование с помощью встроенного в Google App Engine с помощью созданного профиля тестирования "hosted mode", созданного junitCreator. Когда я запускаю тест, я продолжаю получать ошибки, говоря что-то вроде

Starting HTTP on port 0
   HTTP listening on port 49569
The development shell servlet received a request for 'greet' in module 'com.google.gwt.sample.stockwatcher.StockWatcher.JUnit.gwt.xml' 
   [WARN] Resource not found: greet; (could a file be missing from the public path or a <servlet> tag misconfigured in module com.google.gwt.sample.stockwatcher.StockWatcher.JUnit.gwt.xml ?)
com.google.gwt.user.client.rpc.StatusCodeException: Cannot find resource 'greet' in the public path of module 'com.google.gwt.sample.stockwatcher.StockWatcher.JUnit'

Я надеюсь, что кто-то где-то успешно выполнил тест junit (используя GWTTestCase или просто TestCase), который позволит тестировать RPC gwt. Если это так, не могли бы вы упомянуть шаги, которые вы предприняли, или еще лучше, просто отправьте работающий код. Спасибо.

Ответы [ 2 ]

1 голос
/ 08 марта 2012

Я получил это работает. Этот ответ предполагает, что вы используете Gradle, но его легко можно использовать для запуска из муравья. Во-первых, вам нужно убедиться, что вы отделяете свои тесты GWT от своих обычных тестов JUnit. Я создал «тесты / автономные» для обычных тестов и «тесты / gwt» для моих тестов GWT. В конце концов я все еще получаю один HTML-отчет, содержащий всю информацию.

Далее, вам нужно убедиться, что JUnit является частью вашего пути к муравьям, как описано здесь:

http://gradle.1045684.n5.nabble.com/Calling-ant-test-target-fails-with-junit-classpath-issue-newbie-td4385167.html

Затем используйте что-то похожее на это, чтобы скомпилировать ваши тесты GWT и запустить их:

    task gwtTestCompile(dependsOn: [compileJava]) << {
    ant.echo("Copy the test sources in so they're part of the source...");
    copy {
        from "tests/gwt"
        into "$buildDir/src"
    }
    gwtTestBuildDir = "$buildDir/classes/test-gwt";
    (new File(gwtTestBuildDir)).mkdirs()
    (new File("$buildDir/test-results")).mkdirs()

    ant.echo("Compile the tests...");
    ant.javac(srcdir: "tests/gwt", destdir: gwtTestBuildDir) {
        classpath {
            pathElement(location: "$buildDir/src")
            pathElement(location: "$buildDir/classes/main")
            pathElement(path: configurations.runtime.asPath)
            pathElement(path: configurations.testCompile.asPath)
            pathElement(path: configurations.gwt.asPath)
            pathElement(path: configurations.gwtSources.asPath)
        }
    }

    ant.echo("Run the tests...");
    ant.junit(haltonfailure: "true", fork: "true") {
        classpath {
            pathElement(location: "$buildDir/src")
            pathElement(location: "$buildDir/classes/main")
            pathElement(location: gwtTestBuildDir)
            pathElement(path: configurations.runtime.asPath)
            pathElement(path: configurations.testCompile.asPath)
            pathElement(path: configurations.gwt.asPath)
            pathElement(path: configurations.gwtSources.asPath)
        }
        jvmarg(value: "-Xmx512m")
        jvmarg(line: "-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005")
        test(name: "com.onlyinsight.client.LoginTest", todir: "$buildDir/test-results")
        formatter(type: "xml")
    }
}

test.dependsOn(gwtTestCompile);

Наконец, вот простой тест GWT:

public class LoginTest extends GWTTestCase  
{
    public String getModuleName()
    {
        return "com.onlyinsight.ConfModule";
    }

    public void testRealUserLogin()
    {
        UserServiceAsync userService = UserService.App.getInstance();

        userService.login("a", "a", new AsyncCallback<User>()
        {
            public void onFailure(Throwable caught)
            {
                throw new RuntimeException("Unexpected Exception occurred.", caught);
            }

            public void onSuccess(User user)
            {
                assertEquals("a", user.getUserName());
                assertEquals("a", user.getPassword());
                assertEquals(UserRole.Administrator, user.getRole());
                assertEquals("Test", user.getFirstName());
                assertEquals("User", user.getLastName());
                assertEquals("canada@onlyinsight.com", user.getEmail());

                // Okay, now this test case can finish.
                finishTest();
            }
        });

        // Tell JUnit not to quit the test, so it allows the asynchronous method above to run.
        delayTestFinish(10 * 1000);
    }
}

Если в вашем экземпляре RPC нет удобного метода getInstance (), добавьте его:

public interface UserService extends RemoteService {

    public User login(String username, String password) throws NotLoggedInException;

    public String getLoginURL(OAuthProviderEnum provider) throws NotLoggedInException;

    public User loginWithOAuth(OAuthProviderEnum provider, String email, String authToken) throws NotLoggedInException;

    /**
     * Utility/Convenience class.
     * Use UserService.App.getInstance() to access static instance of UserServiceAsync
     */
    public static class App {
        private static final UserServiceAsync ourInstance = (UserServiceAsync) GWT.create(UserService.class);

        public static UserServiceAsync getInstance()
        {
            return ourInstance;
        }
    }
}

Надеюсь, это поможет.

1 голос
/ 14 марта 2010

SyncProxy позволяет вам выполнять вызов GWT RPC из Java. Таким образом, вы можете протестировать свой GWT RPC с обычным Testcase (и быстрее, чем GwtTestcase)

См
http://www.gdevelop.com/w/blog/2010/01/10/testing-gwt-rpc-services/
http://www.gdevelop.com/w/blog/2010/03/13/invoke-gwt-rpc-services-deployed-on-google-app-engine/

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...