Last active
June 10, 2016 23:00
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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