azure-event-hubs-go icon indicating copy to clipboard operation
azure-event-hubs-go copied to clipboard

Mock calls to AMQP in tests

Open devigned opened this issue 6 years ago • 1 comments

Expected Behavior

Tests will execute without needing a connection to an AMQP broker. This will allow quicker validation for pull requests.

Actual Behavior

Tests require authentication and connection to Event Hubs.

devigned avatar Apr 10 '18 22:04 devigned

For what it's worth, what I did was used vburenin/ifacemaker to generate interfaces for the vcabbage/amqp objects (i.e. Client, Session, Receiver and Sender); created thin interface implementations that delegated to the actual vcabbage/amqp library. Then used counterfeiter to generate the mocks.

ifacemaker -f vendor/pack.ag/amqp/client.go -s Client -i amqpClient -p amqp -o _output-directory_

Generated Output:

// Connection ...
type Connection interface {
	// Close disconnects the connection.
	Close() error
	// NewSession opens a new AMQP session to the server.
	NewSession(opts ...amqp.SessionOption) (Session, error)
}

Example wrapper:

func Dial(addr string, opts ...amqp.ConnOption) (Connection, error) {
    amqpClient, err := amqp.Dial(addr, opts...)
    if err != nil {
        return nil, err
    }
    return &connection{client: amqpClient}, nil
}

type connection struct {
    client *amqp.Client  
}

// Close disconnects the connection.
func (c *connection) Close() error {  
   return c.client.Close()  
}

// NewSession opens a new AMQP session to the server.
func (c *connection) NewSession(opts ...amqp.SessionOption) (Session, error) {
    amqpSession, err := c.client.NewSession(opts...)
    if err != nil {
        return nil, err
    }
    return &session{session: amqpSession}, nil
}

Generate the mock

counterfeiter -o _output_location _interface_generated_above_ Client

Then in the code that called the Dial function, I created an unexported var initialized to the amqp.Dial function. In the tests, I replaced the value of this var with the test Dial method above.

Hope that helps

talmdal avatar Feb 21 '19 17:02 talmdal