不好意思承认,但单元测试对我来说还是个新鲜事物。我对如何妥善处理事情有相当坚定的把握。但我发现很难理解的一种情况是,当为一个方法编写一个单元测试时,它只返回依赖方法调用的结果。
.
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
单元测试是测试方法中的逻辑,而不是依赖项的逻辑。那么,在这种情况下,如果只是测试一个模拟依赖项的返回值,那么编写一个测试是否有意义呢?