I am using VS Unit and Moq for unit testing and I cannot figure out the correct place to put my mock setups.

Currently I am setting up mocks like this:

[TestMethod]
public void SomeTestMethod()
{
    // Arrange: ...
    mockRepository.Setup(repo => repo.SomeRepoMethod()).Returns(someMockData);

    // Act: ...   
    // Assert: ...            
}

I find that mocking methods inside each test method makes my code less DRY as I have to copy-paste to any test method that needs a mock implementation of SomeRepoMethod.

Is this the norm or should I move my setups to a common place like ClassInitialize?

有帮助吗?

解决方案

My rule of thumb is that if the mock is used in every test in the class, then I will set it up in ClassInitialize. If only some use it, then I will create a non test method in the class and then call that from any test which needs the mocked objects.

其他提示

Mocking is something which we do to create environment to test particular scenario. For example if you have a Pop up window which gets input from the user. If you need to write Unit tests to test such screen, in this case if you mock such Pop us in each Test test method will become repetitive. In such cases create it once in ClassInitialize will help.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top