我有一个Project
实体,其中包含一组Word
实体。我的WordsRepository
取决于Project
实体。它应该对项目包含的单词集进行操作。
public interface IWordsRepository
{
List<Word> FetchAll();
}
public class WordsRepository : IWordsRepository
{
private readonly Project _project;
public WordsRepository(Project project)
{
if (project == null)
throw new ArgumentNullException("project");
this._project = project;
}
public List<Word> FetchAll()
{
// code for retrieveing words for the project from the database
}
}
现在让我们深入挖掘一下。这是我的ProjectsModel
。
public class ProjectsModel
{
private readonly IProjectsRepository _rep;
private IWordsRepository _wordsRep;
private IProjectsModelObserver _presenter;
// Regular contructor for usual purpose
public ProjectsModel()
{
this._rep = new ProjectsRepository(Program.context);
}
public ProjectsModel(IProjectsRepository repository)
{
this._rep = repository;
}
public virtual void AttachPresenter(IProjectsModelObserver observer)
{
this._presenter = observer;
}
public List<Project> projects
{
get
{
List<Project> tmpList = _rep.FetchAll();
return (tmpList != null) ? tmpList : new List<Project>();
}
}
private Project _selectedProject;
public Project selectedProject
{
get
{
if (_selectedProject == null)
_selectedProject = projects.FirstOrDefault();
return _selectedProject;
}
set
{
if (!projects.Contains(value))
throw new InvalidOperationException("Project not in the Projects list");
_selectedProject = projects[projects.IndexOf(value)];
// Recreating Words repository depending on project
// Here is my issue:
// As I should recreate the Words repository here, passing a new selected project
// how can I mock it and make this class testable?
this._wordsRep = new WordsRepository(this._selectedProject);
if (this._presenter != null)
this._presenter.SelectedProjectChanged(_selectedProject);
}
}
private List<Word> _words;
public List<Word> Words
{
get
{
// Fetching set of words in Project. Just invoking a words repository
}
}
}
当模型的选定项目发生更改时,它应该重新创建WordsRepository
,但不能以这种方式进行测试。
我怎么能嘲笑它?