I have some troubles with mocking of a local variable in a method of my class.
I try to mock my Worker class but it calls a method that returns null value and my context variable becomes null. Thereby I get an exception when try to get the Name property.
How to force CreateWorkerContext()
to return mock values? May be there is a way to mock a local variable (context
)?
Thanks!
My code will tell more about the problem:
namespace Moq
{
class Program
{
static void Main(string[] args)
{
var workerMock = new Mock<Worker>();
workerMock.Object.GetContextName();
}
}
public class Worker
{
public string GetContextName()
{
// something happens and context does not create (imitated situation)
WorkerContext context = CreateWorkerContext();
// exception because _context is null
return context.Name;
}
private WorkerContext CreateWorkerContext()
{
// imitate that context is not created
return null;
}
}
public class WorkerContext
{
public string Name { get; set; }
}
}