考虑以下服务接口:
public interface IServiceA
{
void DoSomething(string s);
void DoSomething(string s, bool b);
}
public interface IServiceB
{
void DoSomething();
}
IServiceB 的实现依赖于 IServiceA,如下所示:
public class ServiceB : IServiceB
{
private IServiceA _serviceA;
public ServiceB(IServiceA serviceA)
{
_serviceA = serviceA;
}
public void DoSomething()
{
_serviceA.DoSomething("Hello", true);
}
}
IE。依赖项被注入到构造函数中。
现在考虑一个单元测试DoSomething()
方法。我希望断言 IServiceA 中的重载 DoSomething 方法之一被调用,但遵循单元测试不应该过多了解被测试方法的内部工作原理的一般原则,我希望不知道哪个是调用了两个重载。考虑以下单元测试:
[TestFixture]
public class ServiceBTests
{
[Test]
public void DoSomething_CallsServiceA()
{
var serviceAMock = MockRepository.GenerateMock<IServiceA>();
var service = new ServiceB(serviceAMock);
service.DoSomething();
// Problem: How to check if EITHER:
serviceAMock.AssertWasCalled(s => s.DoSomething(Arg<String>.Is.NotNull, Arg<bool>.Is.Anything));
// OR:
serviceAMock.AssertWasCalled(s => s.DoSomething(Arg<String>.Is.NotNull));
}
}
我怎样才能断言either one or调用了两个方法中的另一个?
您可以手动设置布尔标志,如下所示:
[TestFixture]
public class ServiceBTests
{
[Test]
public void DoSomething_CallsServiceA()
{
var serviceAMock = MockRepository.GenerateMock<IServiceA>();
bool called = false;
serviceAMock.Stub(
x => x.DoSomething(Arg<String>.Is.NotNull, Arg<bool>.Is.Anything))
.WhenCalled(delegate { called = true; });
serviceAMock.Stub(x => x.DoSomething(Arg<String>.Is.NotNull))
.WhenCalled(delegate { called = true; });
var service = new ServiceB(serviceAMock);
service.DoSomething();
Assert.IsTrue(called);
}
}
但我认为这不是很有用。单元测试涉及从组件边界之外可观察到的任何内容。对模拟的方法调用是其中的一部分。换句话说,如果您测试正在调用的特定重载就可以了。毕竟,您使用该重载而不是另一个重载一定是有原因的。
如果您确实希望单元测试对实现一无所知,则根本不允许您在模拟上断言方法调用。这将严重限制您编写测试的能力。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)