I want to mock a partial class with a private method. But the arranged method is not called. Instead just the normal one. I don't get any errors. It's not relevant what GetAppleModel originally does since it shouldn't do anything in my Test Case. I want the complete body of GetAppleModel to do nothing and only return the task
Test Code:
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();
}
I found an example from a JustMock developer:
Example:
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);
}
Still can't get it work though...
I got it to work. You need to actually use a dynamic wrapper:
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