它是一种代码气味来注入一个依赖关系,并将其属性设置为当前实例?我以这种方式设置我的代码,所以我可以完全隔离服务实现.我有一系列测试全部通过(包括在逻辑类中设置StreamingSubscriber实例).
例如
public class StreamingSubscriber { private readonly ILogic _logic; public StreamingSubscriber(ILogic logic) { _logic = logic; // Not sure I like this... _logic.StreamingSubscriber = this; } public void OnNotificationEvent(object sender,NotificationEventArgs args) { // Do something with _logic var email = _logic.FetchEmail(args); // consume the email (omitted for brevity) } } public class ExchangeLogic : ILogic { public StreamingSubscriber StreamingSubscriber { get; set; } public void Subscribe() { // Here is where I use StreamingSubscriber streamingConnection.OnNotificationEvent += StreamingSubscriber.OnNotificationEvent; } public IEmail FetchEmail(NotificationEventArgs notificationEventArgs) { // Fetch email from Exchange } }
如果这是一个代码气味你怎么去修复它?
编辑
我选择这个实现的原因是因为我想要测试当来自ExchangeLogic的streamingConnection被调用时它会消耗该电子邮件.目前的设计虽然不完美,但允许我编写类似这样的测试.
[Test] public void FiringOnNotificationEvent_WillConsumeEmail() { // Arrange var subscriber = new StreamingSubscriber(ConsumerMock.Object,ExchangeLogicMock.Object); // Act subscriber.OnNotificationEvent(It.IsAny<object>(),It.IsAny<NotificationEventArgs>()); // Assert ConsumerMock.Verify(x => x.Consume(It.IsAny<IEmail>()),Times.Once()); }
现在,如果没有进行完整的集成测试,这显然是无法实现的.如果我告诉我的ExchangeLogic消费电子邮件.