There is a generic class that describes repositories. Here is the code

public class BaseServices<T> : IBaseService<T> where T : BaseEntity, new() { public List<T> AllItem = new List<T>(); public bool Delete(int id) { bool b = false; foreach (var a in AllItem) { if (a.Id == id) { AllItem.Remove(a); b = true; } } return b; } public T Get(int id) { T b = null; foreach (var a in AllItem) { if (a.Id == id) { b = a; return b; } } return b; } public object GetAll() { object b = null; foreach (var a in AllItem) { b = a; return b; } return b; } public bool Save(T entity) { entity = new T(); AllItem.Add(entity); return true; } } 

And there is a test

 List<AccountModel> Accounts = new List<AccountModel>(); private BaseServices<AccountModel> AccountBS = new BaseServices<AccountModel>(); Random rnd = new Random(); public void Repletion() { for (int index = 0; index < 100; ++index) { AccountBS.AllItem[index] = new AccountModel(); AccountBS.AllItem[index].Id = index; } } [TestMethod] public void GetTest() { int SomeId = rnd.Next(100); AccountModel result = AccountBS.Get(SomeId); Assert.IsNotNull(result); } 

For some reason, result = null . Tell me please.

    1 answer 1

    Try to fix your code a bit. As I understand it, your Repletion method is something like test initialization, that is, it must be executed before running test methods. Attach the TestInitializeAttribute attribute to TestInitializeAttribute to allocate memory and configure resources to run tests, and use a slightly different approach when adding items to the collection. Either through its own Save method or through the standard add-to-end method: Add :

     private BaseServices<AccountModel> AccountBS = new BaseServices<AccountModel>(); Random rnd = new Random(); [TestInitialize] public void Repletion() { for (int index = 0; index < 100; ++index) { AccountBS.AllItem.Add(new AccountModel { Id = index }); } } [TestMethod] public void GetTest() { int SomeId = rnd.Next(100); AccountModel result = AccountBS.Get(SomeId); Assert.IsNotNull(result); } 

    TestInitializeAttribute - identifies the method that must be run before the test allocates and configures the resources needed by all tests in the test class. This class is not inherited.