Reputation: 1247
I tried to make a unit-testing
of a class User
I tried to do it with an interface, but I did not understand exactly what is and if it is the correct way to do the test, so:
My Class User
public class User : IUser
{
public int id { get; private set; }
public string username { get; set; }
public IUser user;
public User(IUser userI) // constructor with interface
{
user = userI;
}
public virtual bool MyFunction(string test)
{
if(test=="ping")
return true;
else
return false;
}
}
My Interface IUser
public interface IUser
{
int id { get; }
string username { get; set; }
}
And then my Unit-test
[TestFixture]
public class MoqTest
{
[Test]
public void TestMyFunction()
{
var mock = new Mock<IUser>();
User user = new User(mock.Object);
var result = user.MyFunction("ping");
Assert.That(result, Is.EqualTo(true));
}
}
The test result is correct and actually returns true
, but do not understand the way of using the interface.
Upvotes: 0
Views: 3187
Reputation: 37123
Basically by mocking you create some kind of a dummy-implementation for that interface. So when calling Mock<IUser>()
the compiler generates an anonymous class that implements the interface IUser
and returns a new instance of this class. Now when creating your User
-object you inject that dummy-object. The mocked object has no behaviour, all its members are set to to their default-value, it is only guaranteed that theay are set to anything. You can also change the values your members return but that won´t affect your example.
This way you can test the method you´re interested in without having to implement any external dependeines. This can be necessary because you have currently no working instance for the IUSer
-interface and implement it later or because its initialization is quite heavy and you want to avoid initialize it within your tests (think of some database-logic included that does not affect your actual test, but would be needed to run the test).
In your case you could even use new User(null)
as the method to be tested does not rely on an instance of that interface at all. So you won´t even have to mock it at all.
Upvotes: 1