简体   繁体   中英

Unit Test Grails with Service

I'm trying to do a test on controller that uses 3 Domains and a service to perform persistence, when I use these values ​​in view he is saving normally, but in my unit test does not pass validation, I do not understand why . If someone who has been there can help me, I do not know if the Mock I'm doing is correct, I followed the examples in the documentation oficial .

thats the error message:

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

Thats my code for Test:

@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 = "michael.s@mail.com"
        usuarioCommand.login = "login"
        usuarioCommand.senha = "senha"
        usuarioCommand.senhaRepeat = "senha"

        assertTrue( usuarioCommand.validate() );

        controller.usuarioService = service

        controller.create(usuarioCommand)

                assertEquals(1, Usuario.count())
    }

This is my controller action:

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]
    }
}

mockFor would give you back a mock control. You have to explicitly call createMock() on the mock control to get the actual mocked object.

service = mockFor(UsuarioService).createMock()

Have a look at "Mocking Collaborators" from the same link you referred. The test can be optimized if you still face an issue.

similar example and one here .

You need to set an expectation on the UsarioService to say what will be returned when usarioService.save(...) is called.

Before getting to that point, you need to say in the test mockUsarioService.createMock() which will create the actual instance of the mock object, that's what you will pass to the controller usarioService attribute. Copied the code below from the Grails documenation. 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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM