简体   繁体   中英

Mock an interface method that returns a read only struct

I am trying to Mock a method on an interface that returns a read only struct with an internal constructor. Since I need my mocked response to have certain values in the object how can achieve this? I am using XUnit and Moq.

A working example using the redis stack exchange library; This interface IDatabase has a method StreamGroupInfo and the response object is StreamGroupInfo . This response object is read only struct with an internal constructor so i cant simple create an instance of the object and assign my desired values.

You can use Activator.CreateInstance

// Arguments to pass to internal constructor here in order
var args = new object[] { "name", 10, 20, "someId" };
// You need to leave the (Binder) and (CultureInfo) casts so that C# compiler would call the correct overload for Activator.CreateInstance
var obj = (StreamGroupInfo)Activator.CreateInstance(typeof(StreamGroupInfo), BindingFlags.NonPublic | BindingFlags.Instance, (Binder)null, args, (CultureInfo)null);

Please note that in the code above there are two type casts that seem unnecessary (and Visual Studio will recommend that you remove them). But since the value of the parameters is null, C# has no way to know the parameter types. So it will assume type Object and will call the Activator.CreateInstance(Type type, params object[] args) overload which will not work. You can rewrite the code as follows to silence Visual Studio recommending you you remove the casts, and it's only two extra lines/variables.

// Arguments to pass to internal constructor here in order
var args = new object[] { "name", 10, 20, "someId" };
Binder binder = null;
CultureInfo culture = null;
var obj = (StreamGroupInfo)Activator.CreateInstance(typeof(StreamGroupInfo), BindingFlags.NonPublic | BindingFlags.Instance, binder, args, culture);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM