简体   繁体   中英

Accessing virtual method from abstract class using repository pattern

I'm stuck in understanding - how to access and use (or is it even possible to use) base class virtual method.

So the code is: Base class:

public abstract class Vehicle
{
    public string VehicleIdentificationNumber { get; set; }
    public string Make { get; set; }
    public string Model { get; set; }
    public abstract string DisplayName { get; }

    public virtual bool HasAnAmazingColor(){         
    }
}

Repository pattern:

public class VehicleRepository : IVehicleRepository, ICollection
{
    private readonly List<Vehicle> _vehicles;

    public int Count => _vehicles.Count;

    public object SyncRoot => ((ICollection)_vehicles).SyncRoot;

    public bool IsSynchronized => ((ICollection)_vehicles).IsSynchronized;

    public void CopyTo(Array array, int index)
    {
        ((ICollection)_vehicles).CopyTo(array, index);
    }

    public IEnumerator GetEnumerator()
    {
        return ((ICollection)_vehicles).GetEnumerator();
    }

    public VehicleRepository(List<Vehicle> aVehicles)
    {
        _vehicles = aVehicles;
    }

Then int unittest I try to get the virtual method, but do know that I'm not understanding something, but cannot figure out what, how can I use the method without overriding it?

  [TestClass()]
public class VehicleRepositoryTests
{

    private VehicleRepository vehicleList = new VehicleRepository(new List<Vehicle>());

    [TestMethod()]
       public void HasAmazingColor()
    {
        //arrange

        //act
        vehicleList.??? -- I'm missing something 

        //assert           
    }

I can access virtual method in any of the derived class that implements Vehicle, but is there a way to use it in repository pattern?

Well, you have abstract base calls Vehicle .

From careful observation of your code, I found that you have not derived your VehicleRepository Class from Vehicle .

So you will not be able to access the virtual method from Vehicle on VehicleRepository instance.

The method you are looking for HasAmazingColor will be available on every single object in List<Vehicle> _vehicles;

May be you can expose the List of Vehicles as property and then use it in the unit test, just in case you want to use it.

Or

If your design does not allow to explose the _vehicles as public collection, then you can have a public method in VehicleRepository class which internally calls the HasAmazingColor method on appropriate Vehicle object or objects.

The solution will depend on your application design.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM