task4/solution07/test/org/apidesign/apifest08/test/ContractImposingDelegatingConvertor.java
changeset 61 58ec6da75f6f
parent 45 251d0ed461fb
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/task4/solution07/test/org/apidesign/apifest08/test/ContractImposingDelegatingConvertor.java	Sat Oct 11 23:38:46 2008 +0200
     1.3 @@ -0,0 +1,53 @@
     1.4 +/*
     1.5 + * To change this template, choose Tools | Templates
     1.6 + * and open the template in the editor.
     1.7 + */
     1.8 +
     1.9 +package org.apidesign.apifest08.test;
    1.10 +
    1.11 +import java.math.BigDecimal;
    1.12 +import java.util.Currency;
    1.13 +import junit.framework.Assert;
    1.14 +import org.apidesign.apifest08.currency.Convertor;
    1.15 +import org.apidesign.apifest08.currency.DelegatingConvertor;
    1.16 +import org.apidesign.apifest08.currency.MonetaryAmount;
    1.17 +
    1.18 +/**
    1.19 + * A delegating convertor that checks preconditions and postconditions.
    1.20 + * Useful for testing.
    1.21 + * @author jdvorak
    1.22 + */
    1.23 +public class ContractImposingDelegatingConvertor extends DelegatingConvertor {
    1.24 +
    1.25 +    public ContractImposingDelegatingConvertor( final Convertor underlyingConvertor ) {
    1.26 +        super( underlyingConvertor );
    1.27 +    }
    1.28 +
    1.29 +    @Override
    1.30 +    public ConversionResult convert( final ConversionRequest req ) {
    1.31 +        Assert.assertNotNull( "The request", req );
    1.32 +        final ConversionResult result = super.convert( req );
    1.33 +        Assert.assertNotNull( "Result of the convert() call", result );
    1.34 +        final MonetaryAmount netAmount = result.getNetAmount();
    1.35 +        if ( netAmount != null ) {
    1.36 +            Assert.assertEquals( "Converted to a different currency than specified in the request", req.getTgtCurrency(), netAmount.getCurrency() );
    1.37 +        }
    1.38 +        return result;
    1.39 +    }
    1.40 +
    1.41 +    /**
    1.42 +     * Do some tests on our own.
    1.43 +     * @return this
    1.44 +     */
    1.45 +    public Convertor test() {
    1.46 +        try {
    1.47 +            final Currency aCurrency = Currency.getInstance( "EUR" );
    1.48 +            new ConversionRequest( new MonetaryAmount( BigDecimal.ONE, aCurrency ), aCurrency );
    1.49 +            Assert.fail( "Should have thrown an IllegalArgumentException" );
    1.50 +        } catch ( final IllegalArgumentException e ) {
    1.51 +            Assert.assertEquals( "Cannot request conversion from EUR to EUR", e.getMessage() );
    1.52 +        }
    1.53 +        return this;
    1.54 +    }
    1.55 +
    1.56 +}