Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can the GetField() method of the PrivateObject class access a private const string in C# 4.0?

I'm writing a unit test that accesses a file in isolated data storage. The file name is stored in a private const string within the class because I don't use it anywhere else in the whole application.

However, when I run my unit test I get a "Field not found" error when I call the GetField("fieldName") method of the PrivateObject class instance.

string historyFileName = (string)history.GetField("ISOLATED_HISTORY_FILE");
like image 449
gsirianni Avatar asked Feb 25 '23 17:02

gsirianni


1 Answers

Use the overload which you can pass BindingFlags and pass BindingFlags.NonPublic | BindingFlags.Instance.

Have a look here.


UPDATE

I thought you have a field. Const does get replaced by the literal at compile-time. Change to static readonly and pass BindingFlags.NonPublic | BindingFlags.Static.

If you cannot change the source then there is no way

like image 128
Aliostad Avatar answered Apr 28 '23 19:04

Aliostad