代码之家  ›  专栏  ›  技术社区  ›  pim

单元测试方法,它只调用单个依赖方法-c#/xUnit/Moq

  •  2
  • pim  · 技术社区  · 8 年前

    不好意思承认,但单元测试对我来说还是个新鲜事物。我对如何妥善处理事情有相当坚定的把握。但我发现很难理解的一种情况是,当为一个方法编写一个单元测试时,它只返回依赖方法调用的结果。

    .

    public class Foo {
        Bar int;
        Baz string;
    }
    
    public interface IFooRepository {
        Foo GetByBar(bar int);
    }
    
    public interface IFooService {
        Foo GetByBar(bar int);
    }
    
    public class FooService : IFooService {
        private IFooRepository fooRepository;
    
        public FooService(
            IFooRepository fooRepository){
            this.fooRepository = fooRepository; 
        }
    
        public Foo GetByBar(bar int)
        {
            return fooRepository.GetByBar(bar);
        }
    }
    
    [Fact]
    public class FooServiceTests 
    {
        public class GetByBarMethod 
        {
            [Fact]
            public void ShouldReturnBar()
            {
                //arrange
                var expectedFoo = new Foo() { Bar = 1, Baz = "baz" };
                var repo = new Mock<IFooRepository>();
                repo.Setup(r => r.GetByBar(1)).Returns(expectedFoo);
    
                var service = new FooService(repo.Object);
    
                //act
                var result = service.GetByBar(1);
    
                //assert
                Assert.Same(result, expectedFoo);
            }
        }   
    }
    

    我明白 FooService 单元测试是测试方法中的逻辑,而不是依赖项的逻辑。那么,在这种情况下,如果只是测试一个模拟依赖项的返回值,那么编写一个测试是否有意义呢?

    1 回复  |  直到 8 年前
        1
  •  1
  •   Nkosi    8 年前

    这是为了回答你的意见

    有两种方法

    Setup 期望 Verifiable()

    repo
        .Setup(r => r.GetByBar(1))
        .Returns(expectedFoo)
        .Verifiable();
    

    然后在调用后断言它

    //...code removed for brevity
    
    //act
    var result = service.GetByBar(1);
    
    //assert
    repo.Verify(); //Verifies that all verifiable expectations have been met.
    

    第二种是使用类似于 安装程序 在 Verify

    例如

    //...code removed for brevity
    
    //act
    var result = service.GetByBar(1);
    
    //assert
    Assert.Same(result, expectedFoo);
    repo.Verify(r => r.GetByBar(1));
    

    参考 Moq Quickstart

    推荐文章