Skip to content

Instantly share code, notes, and snippets.

@yareally
Last active June 10, 2016 23:00
Show Gist options
  • Save yareally/13f4e06d62aa6706cc59240a38092a08 to your computer and use it in GitHub Desktop.
Save yareally/13f4e06d62aa6706cc59240a38092a08 to your computer and use it in GitHub Desktop.
Using AutoFixture + Moq + Microsoft Fakes to test a static method that calls to some Windows APIs
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.ServiceProcess;
using System.Linq;
using Microsoft.QualityTools.Testing.Fakes;
using Ploeh.AutoFixture;
using Ploeh.AutoFixture.AutoMoq;
using ServicesTool2.Models;
namespace ServicesToolTests {
[TestClass]
public class ServiceHelperTests
{
private string[] servicesToFind;
[TestInitialize]
public void Setup()
{
servicesToFind = new[] { "cc_cticore.exe 1", "cc_cticore.exe 2", "CC_Cticore.exe 3", "CC_APIServer.exe", "cc_ApiServer.exe 2" };
}
[TestMethod]
public void TestCheckInstalledServices()
{
using (ShimsContext.Create()) {
System.ServiceProcess.Fakes.ShimServiceController.GetServices = () => {
var serviceFixture = new Fixture().Customize(new AutoMoqCustomization());
var services = serviceFixture.CreateMany<ServiceController>().ToList();
servicesToFind.ToList().ForEach(service => services.Add(TestHelpers.GenerateService(service)));
return services.ToArray();
};
servicesToFind.ToList()
.ForEach(service => Assert.IsTrue(WindowsServicesHelper.CheckForInstalledService(service)));
Assert.IsFalse(WindowsServicesHelper.CheckForInstalledService("invalidservice.exe"));
}
}
[TestMethod]
public void TestGetCallCopyServices()
{
using (ShimsContext.Create()) {
System.ServiceProcess.Fakes.ShimServiceController.GetServices = () => {
var serviceFixture = new Fixture().Customize(new AutoMoqCustomization());
var services = serviceFixture.CreateMany<ServiceController>().ToList();
servicesToFind.ToList().ForEach(service => services.Add(TestHelpers.GenerateService(service)));
return services.ToArray();
};
var callCopyServices = WindowsServicesHelper.GetCallCopyServices();
callCopyServices.ForEach(service => Assert.IsTrue(servicesToFind.Contains(service.ServiceName)));
}
}
}
public class TestHelpers
{
public static ServiceController GenerateService(string serviceName)
{
var serviceFixture = new Fixture().Customize(new AutoMoqCustomization());
ServiceController coreService = serviceFixture.Build<ServiceController>().With(x => x.ServiceName, serviceName).Create();
return coreService;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment