Usually, I know how to fix this kind of Exception. However, this time, due to it being because of working with Test classes, I am unsure how to pass the correct parameter.
The method that I am testing is Update() inside PhaseController.
public IActionResult Update(int id)
{
string connectionString = Configuration["ConnectionStrings:DefaultConnection"];
Phase phase = new Phase();
using (SqlConnection connection = new SqlConnection(connectionString))
{
string sql = $"Select * From Phases Where Id='{id}'";
SqlCommand command = new SqlCommand(sql, connection);
connection.Open();
using (SqlDataReader dataReader = command.ExecuteReader())
{
while (dataReader.Read())
{
phase.Id = Convert.ToInt32(dataReader["Id"]);
phase.Name = Convert.ToString(dataReader["Name"]);
}
}
connection.Close();
}
return View(phase);
}
And my PhaseControllerTest class is this:
public class PhaseControllerTest
{
public IConfiguration Configuration { get; }
[Fact]
public void TestCreateView()
{
var controller = new PhaseController(Configuration);
var result = controller.Create() as ViewResult;
Assert.Contains("Create", result.ViewName);
}
[Fact]
public void TestUpdateView()
{
Phase phase = new Phase();
phase.Id = 6009;
phase.Name = "Main Phase";
phase.ReleaseId = 3008;
int id = 6009;
var controller = new PhaseController(Configuration);
var result = controller.Update(id) as ViewResult;
Assert.True(phase.Id == ((Phase) result.Model).Id);
}
}
The error I am getting is on this line:
string connectionString = Configuration["ConnectionStrings:DefaultConnection"];
Saying:
System.NullReferenceException: 'Object reference not set to an instance of an object.' Intersection.Controllers.PhaseController.Configuration.get returned null.
How can I insert the Configuration
in the TestUpdateView()
? Preferably, without actually having to write down the whole connection string.