Created
July 3, 2017 12:03
-
-
Save farukterzioglu/12786aae5954178ed0cde97eb06662ce to your computer and use it in GitHub Desktop.
Mocking a method with calculated return value, instead of static return value. (Moq, TDD)
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
namespace MoqNotes | |
{ | |
public interface ISubjectUnderTest | |
{ | |
int GetData(int param); | |
} | |
public class Tests | |
{ | |
[Fact] | |
public void ReturnCalculatedValue() | |
{ | |
//Arrange | |
int valueToReturn = 0; | |
Mock<ISubjectUnderTest> subjectUnderTestMock = new Mock<ISubjectUnderTest>(); | |
subjectUnderTestMock | |
.Setup(x => x.GetData(It.IsAny<int>())) | |
.Callback((int param) => | |
{ | |
valueToReturn = ++param; | |
}) | |
.Returns(()=> valueToReturn); //!!! NOT ".Returns(valueToReturn)", watch out for "()=>" | |
//Act | |
ISubjectUnderTest subjectUnderTest = subjectUnderTestMock.Object; | |
var result = subjectUnderTest.GetData(19); | |
//Assert | |
Assert.Equal(result, 20); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment