JustMock部分class,模拟私有方法
JustMock partial class, mock private method
我想用私有方法模拟部分 class。但是不会调用安排的方法。而只是普通的。我没有收到任何错误。这与 GetAppleModel 最初所做的无关,因为它不应该在我的测试用例中做任何事情。我希望 GetAppleModel 的完整主体什么也不做,只 return 任务
测试代码:
Task<AppleModel> task = new Task<AppleModel>(() => appleModel);
var taskWorker = TaskWorkerFactory.Create(taskModel);
Mock.NonPublic
.Arrange<Task<AppleModel>>((AppleTaskWorker) taskWorker, "GetAppleModel", ArgExpr.IsAny<Guid>())
.DoInstead(() =>
{
//...
})
.Returns(task);
taskWorker.Start();
//Some Assertion
AppleTaskWorker Class:
public async void Start() {
_appleModel = await GetAppleModel(_guid);
}
private async Task<AppleModel> GetAppleModel(Guid serviceGuid)
{
var command = new ServiceCommand(serviceGuid);
await HandlerService.Start(command);
return command.GetResult();
}
我从 JustMock 开发者那里找到了一个例子:
示例:
public class Class1
{
private bool Helper()
{
return true;
}
public bool TestMe()
{
if (Helper()) return true;
return false;
}
}
[TestMethod]
public void TestMethod1()
{
var class1 = new Class1();
Mock.NonPublic.Arrange<bool>(class1, "Helper").Returns(false);
bool actual = class1.TestMe();
Assert.IsFalse(actual);
}
虽然仍然无法正常工作...
我让它工作了。您需要实际使用动态包装器:
Task<AppleModel> task = new Task<AppleModel>(() => appleModel);
var taskWorker = TaskWorkerFactory.Create(taskModel);
dynamic taskWorkerWrapper = Mock.NonPublic.Wrap((AppleTaskWorker)taskWorker);
Mock.NonPublic
.Arrange<Task<AppleModel>>(taskWorkerWrapper.GetAppleModel( ArgExpr.IsAny<Guid>())).Returns(task);
taskWorker.Start();
//Some Assertion
我想用私有方法模拟部分 class。但是不会调用安排的方法。而只是普通的。我没有收到任何错误。这与 GetAppleModel 最初所做的无关,因为它不应该在我的测试用例中做任何事情。我希望 GetAppleModel 的完整主体什么也不做,只 return 任务
测试代码:
Task<AppleModel> task = new Task<AppleModel>(() => appleModel);
var taskWorker = TaskWorkerFactory.Create(taskModel);
Mock.NonPublic
.Arrange<Task<AppleModel>>((AppleTaskWorker) taskWorker, "GetAppleModel", ArgExpr.IsAny<Guid>())
.DoInstead(() =>
{
//...
})
.Returns(task);
taskWorker.Start();
//Some Assertion
AppleTaskWorker Class:
public async void Start() {
_appleModel = await GetAppleModel(_guid);
}
private async Task<AppleModel> GetAppleModel(Guid serviceGuid)
{
var command = new ServiceCommand(serviceGuid);
await HandlerService.Start(command);
return command.GetResult();
}
我从 JustMock 开发者那里找到了一个例子:
示例:
public class Class1
{
private bool Helper()
{
return true;
}
public bool TestMe()
{
if (Helper()) return true;
return false;
}
}
[TestMethod]
public void TestMethod1()
{
var class1 = new Class1();
Mock.NonPublic.Arrange<bool>(class1, "Helper").Returns(false);
bool actual = class1.TestMe();
Assert.IsFalse(actual);
}
虽然仍然无法正常工作...
我让它工作了。您需要实际使用动态包装器:
Task<AppleModel> task = new Task<AppleModel>(() => appleModel);
var taskWorker = TaskWorkerFactory.Create(taskModel);
dynamic taskWorkerWrapper = Mock.NonPublic.Wrap((AppleTaskWorker)taskWorker);
Mock.NonPublic
.Arrange<Task<AppleModel>>(taskWorkerWrapper.GetAppleModel( ArgExpr.IsAny<Guid>())).Returns(task);
taskWorker.Start();
//Some Assertion