How mock and abstract method using moq.

  • Thread starter Thread starter Its me Gopi
  • Start date Start date
I

Its me Gopi

Guest
I am having the following method



public override sealed DeviceResult Start()
{
lock (mLock)
{
IRequest Req = CreateStartRequest();
IResponse Rsp = null;

// get the list of notifications a derived class is interested in
List<Type> Notifs = new List<Type>();
GetNotifications(Notifs);

if (Notifs.Count == 0)
{
throw new ArgumentException(); // must hve at least one notification

// log
}

// subscribe to completion notification
Worker.SubscribeNotification(Notifs, this);

//Debug.WriteLine("Actuator {0} SendRecv", this.GetType());

// Send request and get response
bool Result = Worker.SendRecv(Req, out Rsp);

//Debug.WriteLine("Actuator {0} Done with SendRecv", this.GetType());

// Check for errors
if (Result == false)
{
Debug.WriteLine(String.Format("{0}: could not write start request to MC", this.GetType()));
return DeviceResult.InternalError;
}

// Check if we got a proper response
if (Rsp == null)
{
return DeviceResult.InternalError;
}

if (true == Rsp.IsErrorResponse)
{
Debug.WriteLine(String.Format("{0}: error on start - {1}", this.GetType(), Rsp.ErrorCode));
return new DeviceResult(Rsp.ErrorCode);
}

return DeviceResult.OK;
}
}



protected abstract IRequest CreateStartRequest();

protected abstract void GetNotifications(IList<Type> aNotifications);


I am supposed to write a unit test case for this.


Here CreateStartRequest() and GetNotifications are abstract methods.


I have mocked the CreateStartRequest() method. I am unable to mock the GetNotifications() method.

I am posting the code for the same.

[TestFixtureSetUp]
public void Intilize()
{
var ob = new Mock<IWorker>().Object;
testBaseMock = new Mock<RqRspAsyncComplete>(ob); //(MockBehavior.Default);
var mock = new Mock<IDeviceMessage>();
mock.As<IRequest>();

var testIlist = new Mock<IList<Type>>();

IList<Type> Type = new List<Type>();
object o = new object();
Type.Add(o.GetType());


testBaseMock.Protected().Setup<IRequest>("CreateStartRequest").Returns(mock.Object as IRequest);
testBaseMock.Protected().Setup("GetNotifications", Type);
var mockn = new Mock<IDeviceMessage>();
mockn.As<INotification>();
//typeof(mockn.Object);
List<Type> t = new List<Type>();

t.Add(typeof (object));
object[] arr = new[] {t};
testBaseMock.Protected().Setup("GetNotifications", arr);
}

When the Start() method is called Notifs.Count == 0 becomes zero and throwing error.


Any code is much appericaited.

Continue reading...
 
Back
Top