Mocking IStringLocalizer with nsubstitute

1.3k views Asked by At

I'm trying to get nsubstitute to mock an instance of IStringLocalizer like this

var mock = Substitute.For<IStringLocalizer<SomeClass>>();
mock["Foo"].Returns("Bar");
Assert.That(mock["Foo"], Is.EqualTo("Bar"));

How can I do this?

2

There are 2 answers

0
Anton Komyshan On

Try this:

var mock = Substitute.For<IStringLocalizer<SomeClass>>();

mock["Foo"].Returns(new LocalizedString("Foo", "XXXXXXXA"));
Console.WriteLine(mock["Foo"]); // -> Write "XXXXXXXA"

In documentation of IStringLocalizer you can see that indexer of this type are returns LocalizedString which can not be explicit/implicit cast to System.String so you need to specify explicitly new LocalizedString for Returns method.

0
Alexandre B On

If you want a generic mock that simply returns the ressoure code as translation result, you can use this :

mock[Arg.Any<string>()].Returns(p => new LocalizedString((string)p[0], (string)p[0]));