I have a question about FakeItEasy (or other mock objects since I belive they are pretty similiar). The following is my puesdocode:
public class Service
{
public void CheckService()
{
...
Status status;
if (Getboolean)
{
status = Status.Pass;
}
else
{
status = Status.NotPass;
}
}
public bool Getboolean()
{
.....
if (someConditions)
return true;
else
return false;
}
}
public enum Status
{
Pass = 0,
NotPass = 1
}
Now, I would have to write some unit testing code for the class. Is it possible to mock GetBoolean() while I am really testing Checkservice() with the baseMethod()? If not, how should I modify the code?
Thanks, Kyle
Well even if that were possible, it is more than likely a bad idea. Unit testing CheckService should be testing CheckService only, not Getboolean. There should be a separate unit test for Getboolean which does not depend on any other method.
The correct way to do it would be to have your Getboolean in a different class which inherits from an interface, you would pass that interface into Service constructor (probably using dependency injection), then you could mock that interface and pass in the mock implementation in your unit tests.
Example:
public interface ILogicChecker
{
bool Getboolean();
}
public class LogicChecker : ILogicChecker
{
public bool Getboolean()
{
//.....
if (someConditions)
return true;
else
return false;
}
}
public class Service
{
ILogicChecker logicChecker;
Status status;
public Service(ILogicChecker logicChecker)
{
this.logicChecker = logicChecker;
}
public void CheckService()
{
//...
if (logicChecker.Getboolean())
{
status = Status.Pass;
}
else
{
status = Status.NotPass;
}
}
}
public enum Status
{
Pass = 0,
NotPass = 1
}
Then in your test class (using Moq syntax, sorry I don't know FakeItEasy):
[Test]
public void CheckService_WithTrueGetboolean_ShouldHave_PassStatus
{
//Arrange
var logicCheckerMock = new Mock<ILogicChecker>();
logicCheckerMock.Setup(x => x.Getboolean()).Returns(true);
var service = new Service(logicCheckerMock.Object);
//Act
service.CheckService();
//Assert
Assert.That(service.Status, Is.EqualTo(Status.Pass));
}
[Test]
public void CheckService_WithFalseGetboolean_ShouldHave_NotPassStatus
{
//Arrange
var logicCheckerMock = new Mock<ILogicChecker>();
logicCheckerMock.Setup(x => x.Getboolean()).Returns(false);
var service = new Service(logicCheckerMock.Object);
//Act
service.CheckService();
//Assert
Assert.That(service.Status, Is.EqualTo(Status.NotPass));
}
I think that here there is nothing to Mock. In my opinion, the main purpose of Mock is for example if you have to connecto to a database, then, you Mock the repository and return the data that you want without connect to the database.
But in your method, I think that you can do it without any Mock. i hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With