2013-09-16 132 views
2

我想對使用3域和服務來執行持久性的控制器進行測試,當我在視圖中使用這些值時,他正常保存,但在我的單元測試中沒有通過驗證,我不明白爲什麼。如果有人在那裏可以幫助我,我不知道我所做的模擬是否正確,我遵循文檔oficial中的示例。單元測試Grails與服務

這就是錯誤消息:

junit.framework.AssertionFailedError: expected:<1> but was:<0> 

那是我的代碼測試:

@TestFor(UsuarioController) 
@Mock([SecRole, UsuarioService, Usuario, Cliente, Secuser]) 
@TestMixin(ControllerUnitTestMixin) 
class UsuarioTests { 

    private def usuarioCommand 
    private def service 

    @Before 
    void setUp() { 
     usuarioCommand = mockCommandObject(UsuarioCommand) 
     service = mockFor(UsuarioService) 
    } 

    @Test 
    void testCadastrarUsuarioCorreto() { 

     usuarioCommand.perfil = 2 
     usuarioCommand.nome = "Michael Swaltz" 
     usuarioCommand.cpf = "381.453.718-13" 
     usuarioCommand.email = "[email protected]" 
     usuarioCommand.login = "login" 
     usuarioCommand.senha = "senha" 
     usuarioCommand.senhaRepeat = "senha" 

     assertTrue(usuarioCommand.validate()); 

     controller.usuarioService = service 

     controller.create(usuarioCommand) 

       assertEquals(1, Usuario.count()) 
    } 

這是我的控制器操作:

def create = { UsuarioCommand usuario -> 

    if(!params.create) return 

    if(!usuario.hasErrors()) { 

     def secuser = new Secuser(username: usuario.login, password: usuario.senha, senha: usuario.senhaRepeat, enabled: true) 


     def user = new Usuario(nomeUsuario: usuario.nome, email: usuario.email, cpf: usuario.cpf, idNivelAcesso: usuario.perfil) 
     def cliente = Cliente.findByUsuario(session.usuario) 
     user.setIdCliente(cliente) 

     def secrole = SecRole.get(usuario.perfil) 

     try{ 
      usuarioService.save(user, secuser, secrole) 
      flash.message = "Usuário ${usuario.nome} cadastrado.".toString() 
      redirect (action: 'list') 
     }catch(ValidationException ex) { 
      StringBuilder mensagem = new StringBuilder(); 
      ex.errors.fieldErrors.each { FieldError field -> 
       mensagem.append("O campo ").append(field.field) 
              .append(" da classe ") 
              .append(field.objectName) 
              .append(" com o valor ") 
              .append(field.rejectedValue) 
              .append(" não passou na validação.") 
              .append("\n") 
      } 

      flash.error = mensagem.toString() 
      return [usr: usuario] 
     }catch(ex) { 
      flash.error = ex.message 
      render "Erro" 
      //return [usr: usuario] 
     } 
    }else { 
     usuario.errors.allErrors.each { println it } 
     render "Erro" 
     //return [usr: usuario] 
    } 
} 
+0

在控制器中的create()調用之前設置服務看起來很好(假設您解決mockFor調用如下),但您創建的通話將幾乎立即返回,除非你在一些PARAMS填寫(例如作爲params.create)。 – billjamesdev

回答

4

mockFor會退給你一個模擬的控制。你必須明確地在模擬控件上調用createMock()來獲得實際的模擬對象。

service = mockFor(UsuarioService).createMock() 

查看您引用的同一鏈接中的「Mocking Collaborators」。如果您仍然遇到問題,可以優化測試。

similar example和一個here

+0

仍然是相同的消息。我正在做的'注射'服務是否正確? –

+0

@CarlosEduardo嗯,我沒有看到有問題的服務。 – dmahapatro

1

您需要對UsarioService設置一個期望,以說明在調用usarioService.save(...)時會返回什麼。

在得到這一點之前,您需要在測試 中說mockUsarioService.createMock()它將創建模擬對象的實際實例,這就是您將傳遞給控制器​​usarioService屬性的內容。從Grails文檔複製下面的代碼。 http://grails.org/doc/1.1/guide/9.%20Testing.html

String testId = "NH-12347686" 
    def otherControl = mockFor(OtherService) 
    otherControl.demand.newIdentifier(1..1) {-> return testId } 

    // Initialise the service and test the target method. 
    def testService = new MyService() 
    testService.otherService = otherControl.createMock()