简体   繁体   中英

C# - Unit testing - initializing private fields - ASP.NET Core 5 - NUnit test

I am new to unit testing, and is currently trying to test a method that gets rows of data using Entity Framework from a SQL Server database.

The problem is that I have 3 fields that are private readonly, and I need to pass those three fields to a method. But since I cant make a constructor, all 3 values are null as default.

How do I make initialize private readonly fields, that talk with a database when unit testing?

By definition, a private field cannot be "seen" outside its class and unit tests are outside. You can create a public property to view them or you can unit test a private method but realize that it is a bad practice. Here you can find an example: https://github.com/fredatgithub/Zipfiles/blob/52c14b4967483352f8652bbe97a613181eb2f49e/UnitTestApplication/UnitTestApplication.cs

Here is an example where Deletable is a private method:

[TestMethod]
public void TestMethodDeletable_file_name_is_ok()
{
  PrivateType privateTypeObject = new PrivateType(typeof(Program));
  const string methodName = "Deletable";
  const string source = "logs_20171103";
  const bool expected = true;
  object obj = privateTypeObject.InvokeStatic(methodName, source);
  Assert.AreEqual(expected, (bool)obj);
}

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