0

So, I'm working on some unit tests, and don't understand why this is happening...

That's the method I am trying to test:

public IEnumerable<Produtos> GetAll(string term, int page, int pageSize)
        {
            var products = _repository.GetAllProducts().ToList();

            List<Produtos> produtos = new List<Produtos>();

            products.ForEach(produto =>
                {
                    if (produto.Nome.Contains(term))
                    {
                        produtos.Add(produto);
                    }
                }
            );
        
            if (!(produtos.Count > 0))
            {
                throw new Exception();
            }

            return produtos.Skip((page - 1) * pageSize).Take(pageSize);
        }

That is the Test Class I wrote:

[TestClass]
    public class ProductTests
    {
        private readonly ProductsService _service;

        public ProductTests()
        {
            _service = new ProductsService();
        }
        [TestMethod]
        public void GetAll_RequestProducts_ReturnsProduts()
        {
            var result = _service.GetAll("camisa", 1, 1);

            Assert.IsNotNull(result);
        }
    }

and those are the results:

enter image description here

  • In unit testing you want to have **clean state** prior to every test. Therefore rather than inject _service in a constructor I would recommend try doing it in a `[SetUp]` method. See [nUnit docs here](https://docs.nunit.org/articles/nunit/writing-tests/attributes/setup.html). This ensures that the dependency is injected in a *consistent* way before *every* unit test fires. Most likely what is happening here is that the unit test is ignoring the constructor entirely – Narish Dec 30 '22 at 15:57
  • Also I'm not sure why this question was marked as a duplicate to what a NullReferenceException is generally when this is very clearly a question about how to go about unit testing properly – Narish Dec 30 '22 at 16:00
  • @Narish I also don't get it... maybe the AI here is not as smart as ChatGPT! haha – Paulo Vitor Dec 31 '22 at 20:49

0 Answers0