简体   繁体   English

我应该在单元测试时总是使用Mocks,以便最小化测试范围内的单元

[英]Should I always use Mocks when unit testing for the sake of minimising units in test scope

Consider the following test which confirms that when an object is added to the HttpContentConatiner class it's resulting MD5, which is stored on the content container matches the result of serializing and hashing the body content externally (which is how it would be used). 考虑以下测试,该测试确认当一个对象被添加到HttpContentConatiner类时,它产生的MD5(存储在内容容器中)与外部序列化和散列体内容的结果相匹配(这是它的使用方式)。

[Fact]
public void When_body_added_correctly_MD5_matches_an_external_hash_of_the_same_content()
{
    var contentStub = new object();
    var serializer = new NewtonSoftJsonSerializer();
    var hasher = new Hmac256Hasher();
    var contentContainer = new HttpContentContainer(serializer, hasher);

    contentContainer.AddBody(contentStub);

    Assert.Equal(hasher.Hash(serializer.Serialize(contentStub), "Key"),
                             contentContainer.ContentMD5.Value);

}

In this test I use an actual implementation for both the serializer and the hasher as opposed to mocking out these two objects. 在这个测试中,我使用了序列化器和hasher的实际实现,而不是模拟这两个对象。 This now means that the test depends on both the hasher and the serializer working correctly as their implementations have now been pulled into the test scope which I worry may make my tests brittle. 这现在意味着测试取决于hasher和序列化器正常工作,因为他们的实现现在已被拉入测试范围,我担心这可能会使我的测试变得脆弱。

My Question 我的问题
Given the above example, should I mock the serializer and hasher for maintainability purposes or is it ok to depend on external services like this? 鉴于上面的例子,我是否应该为了可维护性目的而模拟序列化程序和哈希,还是可以依赖这样的外部服务?

New Code based on Answer: 新代码基于答案:

[Fact]
public void When_a_valid_body_is_added_ContentMD5_Value_is_populated()
{
    var serializerMock = new Mock<ISerializer>();
    serializerMock.Setup(serializer => serializer.Serialize(It.IsAny<object>()))
                  .Returns("serializedContent");

    var hasherMock = new Mock<IHasher>();
    hasherMock.Setup(hasher => hasher.Hash(It.IsAny<string>(), It.IsAny<string()))
              .Returns("MD5");

    var contentContainer = 
        new HttpContentContainer(serializerMock.Object, hasherMock.Object);

    contentContainer.AddBody(new object());

    Assert.NotEmpty(contentContainer.ContentMD5.Value);
}

I would prefer to Mock both Hasher as well as the Serializer. 我更喜欢Mock Hasher和Serializer。

Reason - Both Hash and Serialize method of these dependencies could be assumed to perform expected functions, and this can be the expectation of the Mock. 原因 - 可以假设这些依赖关系的HashSerialize方法都执行预期的功能,这可能是模拟的期望。 A test failure would then indicate the failure of Object under test with certainty. 然后,测试失败将确定指示被测对象的失败。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM