简体   繁体   English

带有服务的单元测试网格

[英]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 . 我试图在使用3个域和服务执行持久性的控制器上进行测试,当我使用这些值时考虑到他可以正常保存,但是在我的单元测试中未通过验证,我不明白为什么。 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 . 如果曾经去过那里的人可以帮助我,我不知道我在做的Mock是否正确,我将遵循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. mockFor会给您一个模拟控件。 You have to explicitly call createMock() on the mock control to get the actual mocked object. 您必须在模拟控件上显式调用createMock()以获取实际的模拟对象。

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. 您需要对UsarioService设置期望,以说出调用usarioService.save(...)时将返回的内容。

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. 在达到这一点之前,您需要在测试mockUsarioService.createMock()中说这将创建模拟对象的实际实例,这就是您将传递给控制器​​usarioService属性的内容。 Copied the code below from the Grails documenation. 从Grails文档复制了下面的代码。 http://grails.org/doc/1.1/guide/9.%20Testing.html 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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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