所以我想我会使用一个模拟框架来模拟这个 Repository 类,但这是正确的方法吗?
是的,这是一个完全正确的方法,因为你应该单独测试你的类。即通过模拟所有依赖项。否则,您无法判断您的类是否失败或它的某些依赖项。
我最初编写了我的测试并使其失败,现在我意识到我需要一个存储库并且需要模拟它,所以我必须更改我的测试以适应模拟对象。有点臭?
Extracting classes, reorganizing methods, etc is a refactoring. And tests are here to help you with refactoring, to remove fear of change. It's completely normal to change your tests if implementation changes. I believe you didn't think that you could create perfect code from your first try and never change it again?
If this is the way to go then when would I create the actual User
Repository? Would this need its own test?
You will create a real repository in your application. And you can write tests for this repository (i.e. check if it correctly calls the underlying data access provider, which should be mocked). But such tests usually are very time-consuming and brittle. So, it's better to write some acceptance tests, which exercise the whole application with real repositories.
Or should I just forget about mocking anything?
Just the opposite - you should use mocks to test classes in isolation. If mocking requires lots of work (data access, ui) then don't mock such resources and use real objects in integration or acceptance tests.