![]() This is the manually-created mock class, to use in the unit tests. This is whatever answer we need, for the current unit test. These functions implement the IPlayerDataMapper interface. This lets us "mock" the results that we would receive from a real database. This property holds the value for PlayerNameExistsInDatabase to return. Public class MockPlayerDataMapper : IPlayerDataMapper MockPlayerDataMapper.cs using Engine.Moq The CreateNewPlayer function does some validation, using the “injected” (passed in, as a parameter) IPlayerDataMapper object. PlayerDataMapper.InsertNewPlayerIntoDatabase(name) Throw new ArgumentException("Player name already exists.") If(playerDataMapper.PlayerNameExistsInDatabase(name)) ![]() Throw an exception if there is already a player with this name in the database. Throw new ArgumentException("Player name cannot be empty.") PlayerDataMapper = new PlayerDataMapper() but use a real PlayerDataMapper, when running the program. This allows us to pass in a "mock" PlayerDataMapper (for testing), If a PlayerDataMapper was not passed in, use a real one. ![]() Public static Player CreateNewPlayer(string name, IPlayerDataMapper playerDataMapper = null) Public Player(string name, int experiencePoints, int gold) This class implements IPlayerDataMapper, and accesses the database – making it difficult to use in automated tests. PlayersWithThisName.CommandText = "INSERT INTO Player () VALUES name) Public void InsertNewPlayerIntoDatabase(string name) Result is 0, if no player exists, or 1, if a player already exists Var existingRowCount = (int)playersWithThisName.ExecuteScalar() Get the number of player with this name PlayersWithThisName.CommandText = "SELECT count(*) FROM Player WHERE 'Name' = name) PlayersWithThisName.CommandType = CommandType.Text ![]() Using(SqlCommand playersWithThisName = connection.CreateCommand()) Using(SqlConnection connection = new SqlConnection(_connectionString)) Public bool PlayerNameExistsInDatabase(string name) "Data Source=(local) Initial Catalog=MyGame Integrated Security=True" Private readonly string _connectionString = Public class PlayerDataMapper : IPlayerDataMapper This defines the functions needed in the object that is “injected” into the CreateNewPlayer function – by both the “real” object (which acceses the database), and the “mock” object (which doesn’t need a database). Void InsertNewPlayerIntoDatabase(string name) IPlayerDataMapper.cs namespace Engine.Moqīool PlayerNameExistsInDatabase(string name) ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. Archives
February 2023
Categories |