Reputation: 1201
I'm trying to test a method which throws different exceptions according to the messages in the exceptions it receives.
I'm having a hard time throwing a SOAPFaultException because its constructor expects a SOAPFault which is an interface.
So I need to mock an interface or a different approach. This project uses grails 2.2.4 and junit 4.10.
Any help is appreciated.
The code:
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") }
}
}
Upvotes: 1
Views: 564
Reputation: 27255
If all you want is a simple way to create an instance of SOAPFault you should be able to do something like this...
import javax.xml.ws.soap.SOAPFaultException
import javax.xml.soap.SOAPFault
// ...
new SOAPFaultException({} as SOAPFault)
If you want to provide some method implementations, like getFaultString() for example, you can do someting like this...
import javax.xml.ws.soap.SOAPFaultException
import javax.xml.soap.SOAPFault
// ...
def soapFault = [getFaultString: { 'some message'}] as SOAPFault
new SOAPFaultException(soapFault)
I hope that helps
Upvotes: 2