I’ve the following simplified code which describes my problem:
public interface IMyUser
{
int Id { get; set; }
string Name { get; set; }
}
Which is used in the dataccess layer like this:
public interface IData
{
T GetUserById<T>(int id) where T : IMyUser, new();
}
The userlogic class is defined as follows:
public class UserLogic
{
private IData da;
public UserLogic(IData da)
{
this.da = da;
}
public IMyUser GetMyUserById(int id)
{
return da.GetUserById<MyUser>(id);
}
}
The userlogic uses a MyUSer class which is only visible internally.
I want to use Moq to mock the call to the dataaccess layer. But becuase I cannot access the MyUser class from my unit test code (which is as designed) , I don’t know how to setup moq?
The Moq code should be something like:
var data = new Mock<IData>();
data.Setup(d => d.GetUserById<MyUser ???>(1)).Returns(???);
var logic = new UserLogic(data.Object);
var result = logic.GetMyUserById(1);
How to solve this?
Let me just expand on Sjoerd’s answer. The problem you are facing is due to not being able to access
MyUsertype from the test assembly. That problem is easily fixed withInternalsVisibleToassembly attribute.I would however recommend to rethink your design and get rid of
IMyUserinterface and instead just useMyUserclass (which should be public). Normally you put services behind interfaces, not entities. Are there any good reasons for providing multiple implementations ofIMyUser?Have a look at how much cleaner this implementation is:
There is another solution, if you insist on having
IMyUserinterface and its internal implementation. Your existing solution, if I infer the contents ofIData.GetUserById<T>correctly, goes something like this:The above code is a slight violation of SRP(warning, PDF) and mixes two responsibilities – retrieving an entity from persistent storage and creating an instance of the entity. Not only that, it also puts the creation responsibility on the interface, which is even worse.
Decoupling those responsibilities using Abstract Factory and Dependency Injection(PDF) patterns will lead to much cleaner design that does not suffer from the same problem as before.