Reputation: 353
Currently in a part of my project a domain object like below exists:
public class Address
{
public virtual string HouseName { get; set; }
public virtual string HouseNumber { get; set; }
public virtual string RoadName { get; set; }
public virtual string Postcode { get; set; }
public virtual string District { get; private set; }
}
The District property is a calculated column in the database. Due to the requirements of the data access provider (Entity Framework) a private set is required. This is fine in normal program flow as the District never needs to be set, due to it being updated when an Address record is saved/updated in the database
A method that I want to test looks like this:
public IEnumerable<House> GetHousesWithinSameDistrict (int addressId)
{
var addressToMatch = _addressRepository
.FirstOrDefault(address => address.Id == addressId)
return _houseRepository
.Where(house => house.Address.District == addressToMatch.District)
}
This is causing me problems when I try to set up the addressToMatch variable, as I am unable to set the District property and as such I cannot write a test to check correct matching addresses are returned.
How should I go about setting up an Address object for this test?
Upvotes: 14
Views: 14659
Reputation: 115769
First, a wild guess: maybe a combination of declaring your District
propery as protected internal
plus adding an assembly:InternalsVisibleTo
attribute to your "domain" assembly so that Distinct
could be set from your tests.
class Address
{
public virtual string District { get; protected internal set; }
}
Alternatively, you could add an internal constructor to your Address
class, which would set the value of the District
property. And again, annotate your "domain" assembly with assembly:InternalsVisibleTo
.
Upvotes: 3
Reputation: 23757
This works out of the box if you're using Moq (which the question is tagged with, so I assume you are):
var mockAddress = new Mock<Address>();
mockAddress.SetupGet(p => p.District).Returns("Whatever you want to match");
So a more complete example is:
var mockAddress = new Mock<Address>();
mockAddress.SetupGet(p => p.Id).Returns(42);
mockAddress.SetupGet(p => p.District).Returns("What you want to match");
var mockAddressRepository = new Mock<IRepository<Address>>();
var addresses = new List<Address> { mockAddress.Object };
mockAddressRepository.Setup(p => p.GetEnumerator()).Returns(addresses.GetEnumerator());
var addressToMatch = mockAddressRepository.Object.FirstOrDefault(address => address.Id == 42);
Console.WriteLine(addressToMatch.District);
This outputs the expected value:
What you want to match
Upvotes: 20