I'm working on a project and when attempting to run a unit test to check progress, I get an error:
Initialization method UnitTestProject.UnitTest1.Init threw exception. System.Data.SqlClient.SqlException: Cannot open database "database" requested by the login. The login failed.
Login failed for user 'User\User1'
I've checked that User1 is owner in SQL Server and think I have the connection string right but I must be missing something obvious, please let me know :)
My repository class:
public class Repository
{
private string _connectionString;
public Repository()
{
_connectionString = configurationManager.ConnectionStrings["database"].ConnectionString;
}
public IEnumerable<Person> GetPeople()
{
var people = new List<Person>();
using (SqlConnection connection = new SqlConnection(_connectionString))
{
string commandText = "SELECT dbo.People.Id"
+ ", dbo.People.FirstName"
+ ", dbo.People.LastName"
+ ", dbo.People.Height"
+ ", dbo.People.Weight"
+ "FROM dbo.People";
SqlCommand command = new SqlCommand(commandText, connection);
try
{
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
people.Add(new Person()
{
Id = reader.GetInt32(0),
FirstName = reader.GetString(1),
LastName = reader.GetString(2),
Height = reader.GetDouble(3),
Weight = reader.GetDouble(4)
});
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
return people;
}
}
My connection string in App.config:
add name="database"
connectionString="Data Source=localhost;Initial Catalog=database;Integrated Security=true"
My unit test:
public class UnitTest1
{
private Repository _repo;
[TestInitialize]
public void Init()
{
_repo = new Repository();
_repo.ResetDatabase();
}
[TestMethod]
public void GetPeople()
{
int count = _repo.GetPeople().Count();
Assert.IsTrue(count > 0);
}
}