不好意思承认,但单元测试对我来说还是个新手。我非常清楚如何正确处理事情。但是我发现很难理解的一种情况是,当为一个只返回依赖方法调用结果的方法编写单元测试时。
我发现在您实现服务层以与 DAL 层互操作的情况下会出现几次。
一个简单的代码示例可能会更好地描述我的问题。
Note: The code example below is using c#, xUnit and Moq.
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
单元测试的重点是测试方法内的逻辑,而不是依赖项的逻辑。那么,如果只是测试模拟依赖项的返回值,那么在这种情况下是否还有必要编写测试?
最佳答案
这是为了回答你的评论
Can you explain how you'd assert the method is called?
有两种方式
首先是使 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
Setup
的表达式
例如
//...code removed for brevity
//act
var result = service.GetByBar(1);
//assert
Assert.Same(result, expectedFoo);
repo.Verify(r => r.GetByBar(1));
关于c# - 只调用单一依赖方法的单元测试方法 - c#/xUnit/Moq,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52121867/