Im working on a small desktop app which controls services on a server. For controlling services i am using ServiceController class. What i want to do is; testing my code and abstract the ServiceController class from my code. So i did something like below.
public interface IServiceControllerWrapper
{
string ServerNameOrIP { get; }
int Status { get; }
bool CanStop { get; }
void StartService();
}
public class ServiceControllerWrapper : IServiceControllerWrapper
{
ServiceController _controller;
const string ServiceName = "W3SVC";
public ServiceControllerWrapper(string serverNameOrIP)
{
_controller = new ServiceController(ServiceName, serverNameOrIP);
}
public string ServerNameOrIP { get { return _controller.MachineName; } }
public int Status
{
get
{
switch (_controller.Status)
{
case ServiceControllerStatus.ContinuePending:
case ServiceControllerStatus.PausePending:
case ServiceControllerStatus.Paused:
return 4;
case ServiceControllerStatus.StopPending:
case ServiceControllerStatus.Stopped:
return 0;
case ServiceControllerStatus.StartPending:
case ServiceControllerStatus.Running:
return 1;
default:
return -1;
}
}
}
public bool CanStop
{
get
{
return _controller.CanStop;
}
}
public void StartService()
{
_controller.Start();
}
//shortened
}
and i am using this class within another named ServerContext. Implementation is;
public interface IServerContext
{
string ServerName { get; }
IServerContext Parent { get; }
IServiceControllerWrapper Controller { get; }
bool HasError { get; set; }
int GetServiceStatus();
}
public class ServerContext : IServerContext
{
IServerContext _parent;
IServiceControllerWrapper _controller;
public ServerContext(IServerContext parent, IServiceControllerWrapper wrapper)
{
_parent = parent;
_controller = wrapper;
}
public string ServerName { get { return _controller.ServerNameOrIP; }}
public IServerContext Parent
{
get
{
return _parent;
}
}
public IServiceControllerWrapper Controller
{
get
{
return _controller;
}
}
public bool HasError { get; set; }
public int GetServiceStatus()
{
return _controller.Status;
}
}
My question here is, i am tryint to test ServerContext and ServiceControllerWrapper but i cant manage to create fake objects. this test method always throws exception because ServerName is null.How can i arrange this code to pass test and or how can i test those classes?
[Fact]
public void ServerName_CannotBeEmpty()
{
Mock<IServiceControllerWrapper> _controller = new Mock<IServiceControllerWrapper>();
ServerContext serverContext = new ServerContext(null, _controller.Object);
//this code fails.
serverContext.ServerName.Should().Not.Be.NullOrEmpty();
}
Any suggestions are welcome. Note: i am using moq,xunit and SharpTestsEx libraries for testing.