Skip to content

Unable to mock Table object returned from IDynamoDBContext.GetTargetTable #1310

Closed
@IIFE

Description

@IIFE

Unable to mock Table object returned from IDynamoDBContext.GetTargetTable

I am injecting IDynamoDBContext in a constructor, and then calling GetTargetTable to get the Table object representing the table for an entity. I then use that Table object to carry out some operations on DynamoDB, or to extract metadata about the table (i.e table name, hash key name, etc).

The problem is I cannot find a way to mock the return value of GetTargetTable as the Table class doesn't appear to be mockable.

Expected Behavior

I would expect GetTargetTable to return an interface that defines the operations which can be carried out on an entity's table, rather than the concrete Table implementation.

Current Behavior

GetTargetTable returns concrete class rather than an abstraction (i.e interface)

Possible Solution

Create an interface abstract over the Table class and have GetTargetTabke return the interface.

Steps to Reproduce (for bugs)

Following class shows an example of the issue:

public class EntityBase
{
	public string Id { get; set; }
}
	
public class DynamoDBRepository<TEntity>
	where TEntity : EntityBase
{
	private IDynamoDBContext DbContext { get; }

	private Table Table { get; }

	private ITableMetadata TableMetadata { get; }

	public DynamoDBRepository(IDynamoDBContext dbContext)
	{			
		DbContext = dbContext ?? throw new ArgumentNullException(nameof(dbContext));
			
		Table = DbContext.GetTargetTable<TEntity>()
			?? throw new InvalidOperationException($"Unable to retrieve table information for {typeof(TEntity).FullName} from {nameof(IDynamoDBContext)}");

		TableMetadata = new TableMetadata(Table.TableName, Table.HashKeys?.FirstOrDefault(), Table.RangeKeys?.FirstOrDefault());
	}

	public async Task UpdateAsync(TEntity entity)
	{			
		ExpectedState state = new ExpectedState();
		state.AddExpected(TableMetadata.IdName, ScanOperator.Equal, entity.Id);

                // Cannot mock this.
		await Table.UpdateItemAsync(DbContext.ToDocument(entity), new UpdateItemOperationConfig{ ExpectedState = state});
	}
}

Context

Unable to unit tests services that consume IDynamoDBContext and rely on the instance returned by GetTargetTable to carry out certain operations.

Your Environment

  • AWSSDK.Core version used: 2.1

Metadata

Metadata

Assignees

No one assigned

    Labels

    dynamodbfeature-requestA feature should be added or improved.needs-major-versionCan only be considered for the next major releasep1This is a high priority issuequeuedv4

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions