Farid
Farid

Reputation: 1020

How do I mock a class that takes in T class with constructor parameters but without property?

Given that I have a class of:

public sealed class MySpecification : Specification<MyDomainObject>
{
    // This is all it really is, just a class with constructor that takes in parameters
    // No properties
    public MySpecification(int id)
    {
        Query.Where(x => x.Id == id);
    }
}

In my handler class where it takes care of the logic:

public async Task<MyDomainDto> Handle(MyHandler request, CancellationToken cancellationToken)
{
    var spec = new MySpecification(request.myId);
    var myDomainEntity = await _myRepository.SingleOrDefaultAsync(spec, cancellationToken);

    // bunch of other logics, yada yada
}

I would like to do unit test on the handler. Right now I'm stuck on mocking the repository, this is what I have now:

public class MyHandlerTests
{
    private readonly IRepository<MyDomainObject> _myRepositoryMock;

    public MyHandlerTests()
    {
        _myRepositoryMock = Substitute.For<IRepository<MyDomainObject>>();
        _myRepositoryMock
            .SingleOrDefaultAsync(Arg.Is<MySpecification>(x => x....??? ), Arg.Any<CancellationToken>())
            .Returns(myObject);
    }
}

How do I tell the _myRepositoryMock that if a parameter of type MySpecification is received with parameter of 1234, return myObject.

I've tried with Arg.Is<T>() but this only works if T have property. My T does not have any properties.

Upvotes: 0

Views: 64

Answers (0)

Related Questions