0

Below is my API's Controller Code.

[Route("api/[controller]")]
[ApiController]
public class DataPrizeController : ControllerBase
{
    private readonly PrizeService service;
    private readonly IRepository<Prize> _Prize;
    public DataPrizeController(PrizeService service, IRepository<Prize> _Prize)
    {
        this.service = service;
        this._Prize = _Prize;
    }
    //Get All Prizes
    [HttpGet("GetAll")]
    public Object GetAllPrizes()
    {
        try
        {
            var data = service.GetAllPrizes();
            return data;
        }
        catch (Exception)
        {
            return "Error";
        }
    }
    //Add Prize  
    [HttpPost("AddPrize")]
    public Object AddPrize([FromBody] Prize prize1)
    {
        try
        {
            service.Add(prize1);
            return true;
        }
        catch (Exception)
        {
            return false;
        }
    }

Below is my N unit Test code.

namespace nUnitTest
{
    public class Tests
    {
        private readonly PrizeService service;
        private readonly IRepository<Prize> _Prize;

        [SetUp]
        public void Setup()
        {
        }

        [Test]
        public void Test1()
        {
            var Service = new Mock<IRepository<Prize>>();
            
            Service.Setup(x => x.GetAll());           
            
            var controller = new DataPrizeController(service, _Prize);

            var result = controller.GetAllPrizes();            

            Assert.AreEqual(Service, result);
        }
    }
}

When I start debugging with breakpoints. It is showing exception: First Exception in Controller's "GetAll" Method: System.NullReferenceException: 'Object reference not set to an instance of an object.'

service was null Second Exception in Test Method: NUnit.Framework.AssertionException: ' Expected: <Mock<IRepository:1>> But was: "Error"

Kindly help me. What code should be written here in test class per controllers method.

DavidG
  • 113,891
  • 12
  • 217
  • 223

0 Answers0