How to Set / Mock propety (C#, UnitTest)

62 views Asked by At

I got this:

private List<NameValuePair<CarTemplateType>> m_tempCars
 
public IList<NameValuePair<CarTemplateType>> CarTypes
{
     get
     {
         if (m_tempCars == null)
         {
             //somelogic
         }

         return m_tempCars;
     }
}

CarsVM has Init where m_tempCars is being setup:

m_tempCars= CarTypes.FirstOrDefault(x => x.Value == my_data.CarTypes);

Now I have TestMethod:

[TestMethod]
Public void SomeTest()
{
CarsVM cars = new CarsVM ();

cars.CarTypes = ??? //

...
}

How to somehow Mock/Set this?

1

There are 1 answers

2
Morten Bork On

If you use Moq:

public class Car : ICar
    {
        public List<CarType> CarTypesList { get; set; }

        public List<CarType> GetCarTypes()
        {
            throw new NotImplementedException();
        }
    }
    
    public interface ICar
    {
        public List<CarType> CarTypesList { get; set; }

        public List<CarType> GetCarTypes();
    }

    public class CarType
    {
        public string Name { get; set; }
    }

    [Fact]
    public void TestCar()
    {
        Mock<ICar> carMock = new Mock<ICar>();
        carMock.Setup(x => x.CarTypesList).Returns(new List<CarType>());
        carMock.Setup(x => x.GetCarTypes()).Returns(new List<CarType>());
        
    }

You can generally make your code more testable by following SOLID principles. They will ensure that your code modules stay small, and easy to test and extend.