Fcbkevin
Fcbkevin

Reputation: 1

Verify parameter of parameter class in moq setup

context.Setup(x => x.ExecuteQuery(It.IsAny<GetBrowserByNameQuery>())).Returns(value: null);

Query class:

public class GetApplicationByNameQuery : IQuery<Application, Application?>
{
    private readonly string _name;

    public GetApplicationByNameQuery(string name)
    {
        _name = name;
    }

    public Application? Execute(IQueryable<Application> queryable)
    {
        return queryable.SingleOrDefault(x => x.Name == _name);
    }
}

GetBrowserByNameQuery requires a string, I do not succeed to test the string passed to GetBrowserByNameQuery.

Following example does not work because it's an other instance of GetBrowserByNameQuery

context.Setup(x => x.ExecuteQuery(new GetBrowserByNameQuery>(command.Name))).Returns(value: null);

Upvotes: 0

Views: 57

Answers (1)

Aleksei Petrov
Aleksei Petrov

Reputation: 1099

You could try following approach:

GetBrowserbyNameQuery resultQuery = null;
context
   .Setup(x => x.ExecuteQuery(It.IsAny<GetBrowserByNameQuery>()))
   .Returns(value: null)
   .Callback<GetBrowserByNameQuery>(query => { resultQuery = query; });

Now in resultQuery you have an actual instance of class, which was used as argument. And you can assert (if class has some public property for Name) with assertion library you use. For example for FluentAssertions:

resultQuery.Name.Should().Be(command.Name)

If GetBrowserByNameQuery doesn't expose Name, there is no easy way to check it. Constructor could not be mocked, so only options you have:

  • access private field via reflections, which is super ugly and breaks unit testing principles
  • wrap creation of a GetBrowserByNameQuery with factory, and then mock the factory and check if factory method was called with a correct argument

Upvotes: 1

Related Questions