I want to test a method with no return, which only runs code if a passed in bool is set to true.
I'd like to test that when the bool is false, no code is called. I expect, this is maybe a case of refactoring to make my code more testable.
Code speaks a thousand words, so here's my method (constructor and dependencies left out for brevity):
...
public void Handle(Notification notification)
{
if (notification.IsRestarting)
{
var installedVersion = _versionService.GetValue("Version");
var packageVersion = "1.0.0";
if (installedVersion.IsNullOrWhiteSpace())
{
_service.Initialise();
}
_versionService.SetValue("Version", packageVersion);
}
}
...
I'm using Moq
for mocking.
The _versionService
actually sets the value in a SQL database table. This is a third-party service, though it is mockable.
So, if isRestarting
is false, the method should do nothing. How do I test this, or make my code more testable?
CodePudding user response:
You can check that your services were never called. Assuming that _versionService
is a Mock<ISomeVersionService>
. Some rough code -
[Test]
public void MyTest()
{
//call the method
Handle(new Notification { IsRestarting = false });
//verify nothing happened
_versionService.Verify(x => x.GetValue(It.IsAny<string>(), Times.Never))
//handle _service similarly
}