Moq C# 调用方法进行测试
Moq C# call method to test
我是 C# 测试的新手,我正在尝试测试一种只增加一些传递的整数值的方法(当用 5 调用它时 returns 6)。我在这里做错了什么? result
始终为 0。
public void TestMethod2()
{
//Act
int numberToCheck = 5;
mock.CallBase = true;
mock.Setup(x => x.CalculateTest(numberToCheck)).Returns(6);
int result = mock.Object.CalculateTest(It.IsAny<int>());
int expected = numberToCheck + 1;
//Assert
Assert.AreEqual(expected, result);
}
您的测试似乎有点毫无意义。看起来你在嘲笑你想要测试的东西。通常你会像这样模拟你想要测试的位周围的所有其他东西:
//This is normally something like a repository that you link to from a service.
//You want the repo to return mocked data so you can see what your service method
//actually does in a set circumstance.
private Mock<ISomethingEffectingYourTestsToMock> _myMockObject;
private IMyServiceUnderTest _sut;
[TestInitialize]
public void Init()
{
_myMockObject = new Mock<ISomethingEffectingYourTestToMock>(); //mock
_sut = new MyServiceUnderTest(your parameters); //real instance
}
[TestMethod]
public void SomeOtherMethod_should_return_23_if_input_is_20()
{
var mockRepoOutput = 6;
this._myMockObject.Setup(r => r.someMethod(It.IsAny<int>())).Returns(mockRepoOutput);
var inputParam = 20;
var expectedResult = 23;
var result = _sut.SomeOtherMethod(inputParam);
Assert.AreEqual(expectedResult, result);
}
开始编写一套单元测试时需要考虑的事情是常见的模拟数据、模拟设置等。如果您不必在每个测试中都设置模拟数据对象,则可以节省大量时间,并且相反,可以只调用一个方法来获得你需要的东西。
我是 C# 测试的新手,我正在尝试测试一种只增加一些传递的整数值的方法(当用 5 调用它时 returns 6)。我在这里做错了什么? result
始终为 0。
public void TestMethod2()
{
//Act
int numberToCheck = 5;
mock.CallBase = true;
mock.Setup(x => x.CalculateTest(numberToCheck)).Returns(6);
int result = mock.Object.CalculateTest(It.IsAny<int>());
int expected = numberToCheck + 1;
//Assert
Assert.AreEqual(expected, result);
}
您的测试似乎有点毫无意义。看起来你在嘲笑你想要测试的东西。通常你会像这样模拟你想要测试的位周围的所有其他东西:
//This is normally something like a repository that you link to from a service.
//You want the repo to return mocked data so you can see what your service method
//actually does in a set circumstance.
private Mock<ISomethingEffectingYourTestsToMock> _myMockObject;
private IMyServiceUnderTest _sut;
[TestInitialize]
public void Init()
{
_myMockObject = new Mock<ISomethingEffectingYourTestToMock>(); //mock
_sut = new MyServiceUnderTest(your parameters); //real instance
}
[TestMethod]
public void SomeOtherMethod_should_return_23_if_input_is_20()
{
var mockRepoOutput = 6;
this._myMockObject.Setup(r => r.someMethod(It.IsAny<int>())).Returns(mockRepoOutput);
var inputParam = 20;
var expectedResult = 23;
var result = _sut.SomeOtherMethod(inputParam);
Assert.AreEqual(expectedResult, result);
}
开始编写一套单元测试时需要考虑的事情是常见的模拟数据、模拟设置等。如果您不必在每个测试中都设置模拟数据对象,则可以节省大量时间,并且相反,可以只调用一个方法来获得你需要的东西。