开发者

Altering fake repository for unit testing when using dependency injection

In my program I have a situation that I can simplify to the following:

  • An IRepository of which I create a MemoryRepository and a SqlRepository implementation
  • A Mapper that gets the IRepository constructor injected.
  • A Mapper.Map() that contains business logic I want to test

I created a test where the Mapper receives the MemoryRepository. By explici开发者_运维百科tly setting a property on the memory repository that will be used in the business logic I can now test this logic. If I use injection however, I wouldn't have access to this repository anymore.

A bit of code tells you more then a 1000 normal words, here is the pastebin link.

How would you go about this?


If I understand your question correctly basically you are concerned that your repository was created AND injected when the test class was instantiated and so in your test method you cannot modify the state of your repository since it is already inside your mapper and, of course, your mapper should not expose the internals of the repository.

If that is the case then I don't think you have to worry, just modify the state of the myMemoryCategoryRepository and execute the mapper's method. Your mapper should behave accordingly because what you injected is a reference to the repository so the object inside the mapper is the same one as the one you would be modifying.

Dim myMemoryCategoryRepository As MemoryCategoryRepository = MemoryKernel.Instance.Get(Of MemoryCategoryRepository)()
Dim myCategoryMapper As CategoryMapper = New CategoryMapper(myMemoryCategoryRepository)

<TestMethod()> _
    Public Sub GetCategoryStartDate_CategoryStartDateAndContractStartDate_ContractStartDateIsOldestDate()

   myMemoryCategoryRepository.AnyFlag = True
   myCategoryMapper.Execute()
   Assert.AreEqual(expectedValue, myCategoryMapper.Value)
End Sub


Not entirely sure what you're asking here, are you testing the mapper or the repository? If you're testing the mapper, then fake the repository. You've already got the seams in place, either use a framework or create a fake repository manually in your tests that makes whatever happy noises you want for the sake of testing Mapper and create the mapper by passing in your fake into the constructor.

So by your own simplification,

  • Create a fake Repository inheriting from IRepository
  • Inject the fake into your Mapper that you are going to test
  • Test Mapper.Map()

If you need to verify some information on the Repository, use a Mock rather than a Stub.

Difference Between Mocks and Stubs

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜