Created
November 19, 2014 08:01
-
-
Save halkeye/ac60f9edde682b316449 to your computer and use it in GitHub Desktop.
Ugly attempt at mocking out static class
This file contains hidden or 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 Moq; | |
| namespace UnitTestStatic | |
| { | |
| public class Utilities : IUtilities | |
| { | |
| private static IUtilities _instance = new Utilities(); | |
| private Utilities() { } | |
| public static IUtilities Instance | |
| { | |
| get { return _instance; } | |
| } | |
| public static string Method1() | |
| { | |
| return Utilities.Instance.Method1(); | |
| } | |
| string IUtilities.Method1() | |
| { | |
| return "a"; | |
| } | |
| } | |
| public interface IUtilities | |
| { | |
| string Method1(); | |
| } | |
| [TestClass] | |
| public class UnitTest1 | |
| { | |
| [TestMethod] | |
| public void TestMethod1() | |
| { | |
| IUtilities unused = Utilities.Instance; | |
| System.Reflection.FieldInfo instance = typeof(Utilities).GetField("_instance", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic); | |
| var mock = new Mock<IUtilities>(); | |
| mock.Setup(item => item.Method1()).Returns("b"); | |
| instance.SetValue(null, mock.Object); | |
| string ret = Utilities.Method1(); | |
| StringAssert.StartsWith(ret, "b"); | |
| } | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
#38 is only needed if you instantiate instance on demand vs create it initially like I did (too lazy to update example right now)