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") }
}
}
非常感謝!測試現在正在工作。 – lsborg