1
votes

I'm testing this factory

    public class ContratoFactory : IContratoFactory
    {
        private readonly IContratoPodeSerCriadoValidation _contratoPodeSerCriadoValidation;

        public ContratoFactory(IContratoPodeSerCriadoValidation contratoPodeSerCriadoValidation)
        {
            _contratoPodeSerCriadoValidation = contratoPodeSerCriadoValidation;
        }

        public async Task<IValidationResult> Build(Contrato entity)
        {
            try
            {
                var result = _contratoPodeSerCriadoValidation.Valid(entity);
            }
            catch (Exception ex)
            {

                // throw 
            }
        }

        public async Task AdicionarLocalBase(Contrato entity)
        {
        }
    }

and here is my test class

    [TestClass]
    public class ContratoFactoryTests
    {
        private IContratoPodeSerCriadoValidation _contratoPodeSerCriadoValidation;
        private ContratoFactory _contratoFactory;

        [TestInitialize]
        public void Initialize()
        {
            _contratoPodeSerCriadoValidation = Substitute.For<IContratoPodeSerCriadoValidation>();
            _contratoFactory = new ContratoFactory(_contratoPodeSerCriadoValidation);
        }

        [TestMethod]
        public async Task AoSerCriadoOContratoDeveSerValidado()
        {
            var contrato = ContratoValues.ContratoComEmpresaENomeValido;
            await _contratoFactory.Build(contrato);
            _contratoPodeSerCriadoValidation.Valid(contrato).Received();
        }
    }

When I run my tests, the thes does not run, or return a "Inconclusive" result.

How can I test Async calls using NSubstitute and FluentAssertions?

UPDATE 19/05/16

I fixed the test methods to return Task instead of void and the tests throws NullReferenceExceptions

1
First thing to fix - change your test method to return Task, not void. That may not be all you need to do, but you should certainly do it. - Jon Skeet
Thanks =] id Works. And It makes my async tests run. Now, I'm having a NullReferenceObject exception. - Jedi31
You should update your question with the updated information or delete your question - Scott Chamberlain
I don't see any usage of Fluent Assertions. - Dennis Doomen

1 Answers

2
votes

I just copy/pasted your code and added a couple of empty interfaces and classes for the missing types. The tests ran just fine out of the box.

As for your question, "How can I test Async calls using NSubstitute and FluentAssertions?", here is how to check for exceptions from an async method.

Func<Task> action = async () => await _contratoFactory.Build(contrato);
action.ShouldThrow<SomeValidationFailedException>();