如何在Flex / AS3中使用基于cookie的会话测试服务

时间:2011-07-06 01:45:16

标签: flex cookies service tdd robotlegs

第一次在这里发帖。感谢您抽出宝贵时间来审核这个问题。

由于标题表明问题与flex应用程序的服务层有关。特别是在测试用例类中。要调用服务,用户必须首先通过基于html / CF的页面进行身份验证。一旦完成并且身份验证已经发生,用户将被定向到嵌入了flex应用程序的html页面。一旦经过身份验证,服务器端CF代码就会将cookie写入用户计算机。然后,flex应用程序将读取此cookie,并且Flex应用程序需要调用CF服务。

问题是:如何在flex app中的服务类的测试用例类中处理它?基本上需要执行以下步骤:使用一些帐户数据来访问服务器并进行身份验证,然后需要编写cookie(它已经存在),然后测试用例需要从cookie中获取会话ID并通过它是测试用例中的服务调用。对于测试用例类来说,这一切似乎都太过分了。

那么,这种事情通常是如何处理的。从我收集的内容来看,Web服务调用通常需要像这样的会话ID。

非常感谢任何想法,意见,建议等。

感谢您抽出时间和任何可以提供的信息。

肖恩

1 个答案:

答案 0 :(得分:3)

将在集成测试中测试cookie和实际服务调用。 Yoyou认为这些位不适合单元测试是正确的。

我喜欢做的是一个很好的委托(假设您的集成点还没有表达接口)并创建实现我选择的接口的测试委托。 cookie将被“检索”,并且它总是对您的测试有效。如果您需要将其设置为false,请创建另一个测试委托并将其作为依赖项提供。

Mockolate可以走很长的路,但建立坚固的模拟是关键。

所以这是一个例子。它没有直接回答你的问题,但我认为它代表了一些相同的问题,因此可能会帮助你解决特定情况。

我正在使用第三方库来处理此应用中的SQL操作。该库有一个名为SQLRunner的核心类。实际上,这个类没有接口(这会使事情变得容易一些)。我有两个选择。

  1. 分叉并修改库以表达接口。
  2. 将SQLRunner包装在我自己的委托类中。
  3. 碰巧,我做了两件事,但出于多种原因更喜欢第二种方法。我能够完全定义第三方库的API和功能。这太棒了。我实际上没有更改API,但是如果你不喜欢它如何命名方法......不用担心,改变它。它还允许我表达一个界面!我最初这样做是因为我想使用Mockolate来模拟其用法。它也可以用来创建我自己的测试模拟,它具有更强大的功能并且更加清晰。所以这是服务:

    public class SQLTaskService extends Actor implements ITaskService
    {
        [Inject]
        public var sqlRunner:ISQLRunnerDelegate;
    
        [Inject]
        public var statusListModel:StatusListModel;
    
        [Inject]
        public var taskListModel:TaskListModel;
    
        public function loadAllTasks():void
        {
            statusListModel.removeAllTasks();
            sqlRunner.execute(LOAD_ALL_TASKS_SQL, null, loadAllTasksResultHandler, Task, databaseErrorHandler);
        }
    
        private function loadAllTasksResultHandler(result:SQLResult):void
        {
            for each(var task:Task in result.data)
            {
                var taskStatus:Status = statusListModel.getStatusFromId(task.statusId);
                statusListModel.addTaskToStatus(task, taskStatus);
                taskListModel.addTask(task);
            }
        }
    
        public function loadTaskById(id:int):void
        {
            sqlRunner.execute(LOAD_TASK_SQL, {taskId:id}, loadTaskResultHandler, Task);
        }
    
        private function loadTaskResultHandler(result:SQLResult):void
        {
            var task:Task = result.data[0] as Task;
            var taskStatus:Status = statusListModel.getStatusFromId(task.statusId);
    
            task = taskListModel.updateTask(task);
    
            statusListModel.addTaskToStatus(task, taskStatus);
        }
    
        public function save(task:Task):void
        {
            var params:Object = task.toParamObject();
    
            sqlRunner.executeModify(Vector.<QueuedStatement>(
                    [new QueuedStatement(SAVE_TASK_SQL, params)]), saveTaskResultHandler, databaseErrorHandler);
        }
    
    
        private function saveTaskResultHandler(results:Vector.<SQLResult>):void
        {
            var result:SQLResult = results[0];
            if (result.rowsAffected > 0)
            {
                var id:Number = result.lastInsertRowID;
                loadTaskById(id);
            }
        }
    
        public function deleteTask(task:Task):void
        {
            sqlRunner.executeModify(Vector.<QueuedStatement>([new QueuedStatement(DELETE_TASK_SQL, {taskId:task.taskId})]),
                    deleteTaskResult, databaseErrorHandler);
        }
    
        private function deleteTaskResult(results:Vector.<SQLResult>):void
        {
            //pass
        }
    
        private function databaseErrorHandler(error:SQLError):void
        {
            dispatch(new DatabaseErrorHandlerEvent(error.message));
        }
    
        [Embed(source="/assets/data/sql/tasks/SaveTask.sql", mimeType="application/octet-stream")]
        private static const SaveTaskStatementText:Class;
        public static const SAVE_TASK_SQL:String = new SaveTaskStatementText();
    
        [Embed(source="/assets/data/sql/tasks/DeleteTask.sql", mimeType="application/octet-stream")]
        private static const DeleteTaskStatementText:Class;
        public static const DELETE_TASK_SQL:String = new DeleteTaskStatementText();
    
        [Embed(source="/assets/data/sql/tasks/LoadTask.sql", mimeType="application/octet-stream")]
        private static const LoadTaskStatementText:Class;
        public static const LOAD_TASK_SQL:String = new LoadTaskStatementText();
    
        [Embed(source="/assets/data/sql/tasks/LoadAllTasks.sql", mimeType="application/octet-stream")]
        private static const LoadAllTasksStatementText:Class;
        public static const LOAD_ALL_TASKS_SQL:String = new LoadAllTasksStatementText();
    }
    

    你可以看到它具有委托依赖:

    /**
     * This is a delegate for the SQLRunner class that allows us to utilize an interface
     * for the purposes of creating mocks. The actual SQLRunner class does not express
     * an interface. This approach also allows us to encapsulate the usage of a 3rd party
     * library into this single delegate.
     *
     * <p>An alternative would be to fork and modify the original library, which would
     * definitely be a viable option and would help others in the future.</p>
     */
    public class SQLRunnerDelegate implements ISQLRunnerDelegate
    {
        private var sqlRunner:SQLRunner;
    
        public function SQLRunnerDelegate(dataBaseFile:File, maxPoolSize:int = 5)
        {
            sqlRunner = new SQLRunner(dataBaseFile, maxPoolSize);
        }
    
        public function get numConnections():int
        {
            return sqlRunner.numConnections;
        }
    
        public function get connectionErrorHandler():Function
        {
            return sqlRunner.connectionErrorHandler;
        }
    
        public function set connectionErrorHandler(value:Function):void
        {
            sqlRunner.connectionErrorHandler = value;
        }
    
        public function execute(sql:String, parameters:Object, handler:Function, itemClass:Class = null, errorHandler:Function = null):void
        {
            sqlRunner.execute(sql, parameters, handler, itemClass, errorHandler);
        }
    
        public function executeModify(statementBatch:Vector.<QueuedStatement>, resultHandler:Function, errorHandler:Function, progressHandler:Function = null):void
        {
            sqlRunner.executeModify(statementBatch, resultHandler, errorHandler, progressHandler);
        }
    
        public function close(resultHandler:Function, errorHandler:Function = null):void
        {
            sqlRunner.close(resultHandler, errorHandler);
        }
    }
    

    结果非常好。现在我的应用程序与第三方库有一个很小的集成点。大赢。我还可以制作健壮的模拟,而无需处理文件系统或第三方库的任何其他奇怪的依赖:

    /**
     * This is a more robust mock for the SQLRunnerDelegate to test for
     * side effects that occur when methods are called on SQLTaskService
     */
    public class MockTaskSQLRunnerDelegate extends MockSQLRunnerDelegateBase implements ISQLRunnerDelegate
    {
        public function execute(sql:String, parameters:Object, handler:Function, itemClass:Class = null, errorHandler:Function = null):void
        {
            lastStatementExecuted = sql;
            allStatementsExecuted.push(lastStatementExecuted);
            parametersSent = parameters;
    
            switch (sql)
            {
                case SQLTaskService.LOAD_ALL_TASKS_SQL:
                    handler.call(null, loadTask());
    
                    break;
    
                case SQLTaskService.LOAD_TASK_SQL:
                    handler.call(null, loadTask());
                    break;
                default:
                    break;
            }
        }
    
        private function loadTask():SQLResult
        {
            var task:Task = new Task();
            var data:Array = [task];
            var result:SQLResult = new SQLResult(data);
    
            task.taskId = 1;
            task.statusId = 1;
    
            return result;
        }
    
        public function executeModify(statementBatch:Vector.<QueuedStatement>, resultHandler:Function, errorHandler:Function, progressHandler:Function = null):void
        {
            lastStatementExecuted = statementBatch[0].statementText;
            allStatementsExecuted.push(lastStatementExecuted);
            parametersSent = statementBatch[0].parameters;
    
            switch (lastStatementExecuted)
            {
                case SQLTaskService.SAVE_TASK_SQL:
                    resultHandler.call(null, saveTask());
                    break;
            }
        }
    
        private function saveTask():Vector.<SQLResult>
        {
            var task:Task = new Task();
            var result:SQLResult = new SQLResult([task], 1, true, 1);
            var results:Vector.<SQLResult> = new Vector.<SQLResult>();
    
            task.taskId = task.statusId = 1;
            results.push(result);
    
            return results;
        }
    
        public function get numConnections():int
        {
            return 0;
        }
    
        public function get connectionErrorHandler():Function
        {
            return null;
        }
    
        public function set connectionErrorHandler(value:Function):void
        {
        }
    
        public function close(resultHandler:Function, errorHandler:Function = null):void
        {
        }
    }
    

    我从这笔交易中得到了一个不错的测试套件:

    public class SqlTaskServiceTest
    {
        private var taskService:SQLTaskService;
    
        [Before(async)]
        public function setup():void
        {
            taskService = new SQLTaskService();
            taskService.statusListModel = new StatusListModel();
            taskService.taskListModel = new TaskListModel();
            initializeModels();
            prepareMockolates();
        }
    
        public function prepareMockolates():void
        {
            Async.proceedOnEvent(this, prepare(ISQLRunnerDelegate), Event.COMPLETE);
        }
    
        [Test]
        public function loadAllTasks_executesSqlStatement_statementEqualsLoadAll():void
        {
            var runner:MockTaskSQLRunnerDelegate = new MockTaskSQLRunnerDelegate();
            taskService.sqlRunner = runner;
    
            taskService.loadAllTasks();
    
            assertThat(runner.lastStatementExecuted, equalTo(SQLTaskService.LOAD_ALL_TASKS_SQL));
        }
    
        [Test]
        public function loadAllTasks_clearsTasksFromStatusListModel_lengthIsEqualToZero():void
        {
            var status:Status = new Status();
            var task:Task = new Task();
    
            initializeModels(status, task);
            taskService.sqlRunner = nice(ISQLRunnerDelegate);
    
            taskService.loadAllTasks();
    
            assertThat(status.tasks.length, equalTo(0))
        }
    
        [Test]
        public function loadAllTasks_updatesTaskListModelWithLoadedTasks_collectionLengthIsOne():void
        {
            taskService.sqlRunner = new MockTaskSQLRunnerDelegate();
    
            taskService.loadAllTasks();
    
            assertThat(taskService.taskListModel.tasks.length, equalTo(1));
        }
    
        [Test]
        public function loadAllTasks_updatesStatusWithTask_statusHasTasks():void
        {
            var status:Status = new Status();
            initializeModels(status);
            taskService.sqlRunner = new MockTaskSQLRunnerDelegate();
    
            taskService.loadAllTasks();
    
            assertThat(status.tasks.length, greaterThan(0));
        }
    
        [Test]
        public function save_executesSqlStatement_statementEqualsSave():void
        {
            var task:Task = new Task();
            var runner:MockTaskSQLRunnerDelegate = new MockTaskSQLRunnerDelegate();
            taskService.sqlRunner = runner;
            task.statusId = 1;
    
            taskService.save(task);
    
            assertThat(runner.allStatementsExecuted, hasItem(SQLTaskService.SAVE_TASK_SQL));
        }
    
        [Test]
        public function save_taskIsLoadedAfterSave_statementEqualsLoad():void
        {
            var task:Task = new Task();
            var runner:MockTaskSQLRunnerDelegate = new MockTaskSQLRunnerDelegate();
            taskService.sqlRunner = runner;
            task.statusId = 1;
    
            taskService.save(task);
    
            assertThat(runner.allStatementsExecuted, hasItem(SQLTaskService.LOAD_TASK_SQL));
        }
    
        [Test]
        public function save_taskIsAddedToModelWhenNew_tasksLengthGreaterThanZero():void
        {
            var taskListModel:TaskListModel = taskService.taskListModel;
            var task:Task = new Task();
    
            taskListModel.reset();
            taskService.sqlRunner = new MockTaskSQLRunnerDelegate();
            task.statusId = 1;
            task.taskId = 1;
    
            taskService.save(task);
    
            assertThat(taskListModel.tasks.length, equalTo(1));
        }
    
        [Test]
        public function save_existingTaskInstanceIsUpdatedAfterSave_objectsAreStrictlyEqual():void
        {
            var taskListModel:TaskListModel = taskService.taskListModel;
            var task:Task = new Task();
            var updatedTask:Task;
    
            taskListModel.addTask(task);
            taskService.sqlRunner = new MockTaskSQLRunnerDelegate();
            task.statusId = 1;
            task.taskId = 1;
    
            taskService.save(task);
            updatedTask = taskListModel.getTaskById(task.taskId);
    
            assertThat(updatedTask, strictlyEqualTo(task));
        }
    
        [Test]
        public function loadTaskById_executesLoadStatement_statementEqualsLoad():void
        {
            var runner:MockTaskSQLRunnerDelegate = new MockTaskSQLRunnerDelegate();
            taskService.sqlRunner = runner;
    
            taskService.loadTaskById(1);
    
            assertThat(runner.allStatementsExecuted, hasItem(SQLTaskService.LOAD_TASK_SQL));
        }
    
        [Test]
        public function deleteTasks_executesDeleteStatement_statementEqualsDelete():void
        {
            var task:Task = new Task();
            var runner:MockTaskSQLRunnerDelegate = new MockTaskSQLRunnerDelegate();
            taskService.sqlRunner = runner;
    
            taskService.deleteTask(task);
    
            assertThat(runner.allStatementsExecuted, hasItem(SQLTaskService.DELETE_TASK_SQL));
        }
    
        private function initializeModels(status:Status = null, task:Task = null):void
        {
            var statusListModel:StatusListModel = taskService.statusListModel;
            statusListModel.reset();
    
            //if nothing was passed in we need to default to new objects
            status ||= new Status();
            task ||= new Task();
    
            status.statusId = 1;
            task.taskId = task.statusId = 1;
    
            statusListModel.statuses.addItem(status);
            statusListModel.addTaskToStatus(task, status);
        }
    }
    

    附注:我想在此指出的是没有一个单一的异步测试。很少需要运行单元测试异步。有些边缘情况你可能真的需要,但它们是例外。