2014-05-21 22 views
1

我試圖測試一個方法,它根據收到的異常中的消息引發不同的異常。如何在grails中模擬與junit的接口

我很難拋出一個SOAPFaultException,因爲它的構造函數需要一個SOAPFault,它是一個接口。

所以我需要模擬一個接口或不同的方法。該項目使用grails 2.2.4和junit 4.10。

任何幫助表示讚賞。

代碼:

import javax.xml.ws.BindingProvider 
import javax.xml.ws.soap.SOAPFaultException 

class CatalogClientService { 
    AplicacaoPT aplicacaoPT = new AplicacaoSoapService().getAplicacaoSoapPort() 
    static transactional = false 

    def fetch(String codigoBuscado) { 
     try { 
      def response = aplicacaoPT.buscaAplicacaoPorCodigo(codigoBuscado) 

      def app = response[0].serviceData.aplicacao[0] 
      def appGeral = app.getGeral() 

      def allTags = app.palavras.palavraChave.findAll().collect { it } 
      def tags = allTags.unique() 

      [name: appGeral.nome, description: appGeral.descricao, tags: tags, admins: [appGeral.getLiderProjeto().getChave()]] 
     } catch (SOAPFaultException e) { 
      if (e.fault.faultString == "Provider Error") { 
       throw new IllegalArgumentException("Nenhuma aplicação encontrada com o código ${codigoBuscado}.", e) 
      } 

      throw new RuntimeException("Erro ao buscar aplicação de código ${codigoBuscado}.", e)     
     } catch (Exception e) { 
      throw new RuntimeException("Erro ao buscar aplicação de código ${codigoBuscado}.", e) 
     } 
    } 
} 


import grails.test.mixin.* 
import grails.test.mixin.support.GrailsUnitTestMixin 
import org.junit.* 
import javax.xml.ws.soap.SOAPFaultException 
import javax.xml.soap.SOAPFault 

@TestFor(CatalogClientService) 
class CatalogClientServiceTests { 

    final shouldFailWithCause = new GroovyTestCase().&shouldFailWithCause 

    void testFetchFailsWithInvalidApplicationCode() { 
     def fault = new Expando() 
     fault.metaClass.getFaultString = { -> "Provider Error" } 
     SOAPFaultException.metaClass.'static'.getFault = { -> fault } 

     AplicacaoPT.metaClass.buscaAplicacaoPorCodigo = { String id -> throw new SOAPFaultException() } 

     shouldFailWithCause(SOAPFaultException) { service.fetch("POPB") }  
    } 
} 

回答

2

如果你想要的是一個簡單的方法來創建的SOAPFault的實例,你應該能夠做這樣的事......

import javax.xml.ws.soap.SOAPFaultException 
import javax.xml.soap.SOAPFault 

// ... 

new SOAPFaultException({} as SOAPFault) 

如果你想提供一些方法實現,比如getFaultString()例如,你可以做些事情是這樣的...

import javax.xml.ws.soap.SOAPFaultException 
import javax.xml.soap.SOAPFault 

// ... 
def soapFault = [getFaultString: { 'some message'}] as SOAPFault 
new SOAPFaultException(soapFault) 

我希望能幫到

+0

非常感謝!測試現在正在工作。 – lsborg