Skip to content

Instantly share code, notes, and snippets.

@ToniRiegler
Created September 27, 2018 14:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ToniRiegler/4812345401f582755e876349978151e2 to your computer and use it in GitHub Desktop.
Save ToniRiegler/4812345401f582755e876349978151e2 to your computer and use it in GitHub Desktop.
FakeItEasy - Faked method calls within tasks don't work all of the time
using System.Threading;
using System.Threading.Tasks;
using FakeItEasy;
using Microsoft.VisualStudio.TestTools.UnitTesting;
public interface ITestInterface
{
int MyMethod();
}
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
ITestInterface fake = A.Fake<ITestInterface>();
int count = 0;
A.CallTo(() => fake.MyMethod()).ReturnsLazily(p => Interlocked.Increment(ref count));
Task<int>[] tasks =
{
Task.Run(() => fake.MyMethod()),
Task.Run(() => fake.MyMethod()),
};
int[] result = Task.WhenAll(tasks).Result;
CollectionAssert.AreEquivalent(new[] {1, 2}, result);
// Assertion fails NEVER with FakeItEasy 2.3.1
// Assertion fails sometimes with FakeItEasy 4.7.1
// Assertion fails sometimes with FakeItEasy 4.9.0
// Message: "Expected to find it twice exactly but found it once among the calls: ..."
A.CallTo(() => fake.MyMethod()).MustHaveHappened(Repeated.Exactly.Twice);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment