Daniel Tigges
Daniel Tigges

Reputation: 31

Mock structs with NSubstitute

i am trying to mock some .NET struct with NSubstitute.

Lets say i got the following struct defined:

 struct MyStruct
 {
      public String CustomString { get; private set; }
 }

No i want to set the return value of that property with NSubstitute:

MyStruct myStruct = new MyStruct();

myStruct.CustomString.Returns("test");

But that doesn't work and throws the following exception:

Could not find a call to return from.

I've also tried to create a Substitute for the struct, but that doesn't work either because a struct isn't a reference type.

So, do you guys know any possible solution to mock a struct ?

Upvotes: 2

Views: 1523

Answers (1)

David Tchepak
David Tchepak

Reputation: 10464

As far as I know this isn't possible. NSubstitute (and many other .NET mocking frameworks) rely on Castle DynamicProxy to mock types. DynamicProxy basically creates a new type on the fly that either implements an interface being mocked, or creates a subclass for a class being mocked.

Because we can't derive from structs in .NET, DynamicProxy will not be able to create this proxy type. Therefore we can't mock it using that approach.

Upvotes: 1

Related Questions