/sigmah/src/test/java/org/sigmah/server/endpoint/gwtrpc/CommandTestCase.java
Java | 91 lines | 59 code | 20 blank | 12 comment | 2 complexity | b3c4875abd16c7ab6850ee126e99e237 MD5 | raw file
1/* 2 * All Sigmah code is released under the GNU General Public License v3 3 * See COPYRIGHT.txt and LICENSE.txt. 4 */ 5 6package org.sigmah.server.endpoint.gwtrpc; 7 8 9import com.google.gwt.user.client.rpc.AsyncCallback; 10import com.google.inject.Inject; 11import com.google.inject.Injector; 12 13import org.sigmah.client.dispatch.AsyncMonitor; 14import org.sigmah.client.dispatch.Dispatcher; 15import org.sigmah.shared.domain.User; 16import org.sigmah.server.util.BeanMappingModule; 17import org.sigmah.server.util.TemplateModule; 18import org.sigmah.shared.command.Command; 19import org.sigmah.shared.command.result.CommandResult; 20import org.sigmah.shared.exception.CommandException; 21import org.sigmah.test.MockHibernateModule; 22import org.sigmah.test.Modules; 23 24import javax.persistence.EntityManager; 25import java.util.Collections; 26import java.util.List; 27 28@Modules({ 29 MockHibernateModule.class, 30 TemplateModule.class, 31 BeanMappingModule.class, 32 GwtRpcModule.class 33}) 34public abstract class CommandTestCase { 35 36 @Inject 37 protected CommandServlet servlet; 38 @Inject 39 protected EntityManager em; 40 41 @Inject 42 protected Injector injector; 43 44 protected int userId = 1; 45 46 47 protected void setUser(int userId) { 48 this.userId = userId; 49 } 50 51 protected <T extends CommandResult> T execute(Command<T> command) throws CommandException { 52 User user = em.find(User.class, userId); 53 assert user != null; 54 55 List<CommandResult> results = servlet.handleCommands(user, Collections.<Command>singletonList(command)); 56 57 // normally each request and so each handleCommand() gets its own 58 // EntityManager, but here successive requests in the same test 59 // will share an EntityManager, which can be bad if there are collections 60 // still living in the first-level cache 61 // 62 // I think these command tests should ultimately become real end-to-end 63 // tests and so would go through the actual servlet process, but for the moment, 64 // we'll just add this work aroudn that clears the cache after each command. 65 em.clear(); 66 67 68 CommandResult result = results.get(0); 69 if (result instanceof CommandException) { 70 throw (CommandException) result; 71 } 72 73 return (T) result; 74 } 75 76 protected Dispatcher dispatcher = new Dispatcher() { 77 78 @Override 79 public <T extends CommandResult> void execute(Command<T> command, 80 AsyncMonitor monitor, AsyncCallback<T> callback) { 81 try { 82 callback.onSuccess(CommandTestCase.this.execute(command)); 83 } catch(Exception e) { 84 System.out.println("Exception thrown while handling command " + command.toString() + ": "); 85 e.printStackTrace(); 86 callback.onFailure(e); 87 } 88 } 89 }; 90 91}