2013-11-28 132 views
2

我是Nunit.please帮助编写测试用例的新手。 这是我的课编写NUnit测试用例的方法

public CommandModule(ICommandFetcher fetcher,ICommandBus commandBus) 
    { 

     //Get["/"] = p => 
     //{z 
     // return Response.AsText((string)Request.Form.Username); 
     //}; 

     Post["/"] = parameters => 
     { 
      var commandRequest = this.Bind<MessageEnvelope>(); 
      var command = fetcher.FetchFrom(commandRequest); 
      commandBus.Send((ICommand)command, commandRequest.MetaData); 
      return HttpStatusCode.OK; 
     }; 
    } 
} 

,我想测试检验这种方法

commandBus.Send((ICommand)command, commandRequest.MetaData); 

谢谢!

我尝试以下方法

[Test] 
    public void whern_reseiving_command_it_sent_to_the_command_bus() 
    { 

     var rCommand = new DummyCommand() { SomeProp = 2 }; 
     var serializedCommand = JsonConvert.SerializeObject(rCommand); 
     var envelope = new MessageEnvelope() { MetaData = new MetaData() { MessageType = "DummyCommand", MessageTypeVersion = 1 }, MessageData = serializedCommand }; 
     var fakeCommand = A.Fake<ICommandBus>(); 

     var browser = new Browser(with => 
     { 
      with.Module<CommandModule>(); 
      with.Dependency<ICommandBus>(fakeCommand); 

     }); 

     var result = browser.Post("/", with => 
     { 
      with.HttpRequest(); 
      with.JsonBody(envelope); 
     }); 

     A.CallTo(() => fakeCommand.Send(rCommand,envelope.MetaData)).MustHaveHappened(); 

A.CallTo(() => fakeCommand.Send(rCommand,envelope.MetaData)).MustHaveHappened(); 它在r命令值某种错误

+0

在编写函数之前,您应该能够编写测试。如果您在编写测试时遇到困难,您必须质疑您是否真正理解实施的要求。从你的命令开始。发送()并问自己你认为应该发生什么。这会导致你写单元测试。 SO读者很难提出单元测试,因为我们不知道你期望发生什么。 –

+0

感谢您的评论 – user3044294

回答

1

这听起来像你正在寻找明确的测试ICommandBus.Send被称为执行代码时。

一种方法是模拟ICommandBus依赖关系。也就是说,插入一个实现ICommandBus的模拟对象,该对象能够检测是否使用正确的参数值调用该方法。

如果你采取这种方法,你通常会使用模拟框架(例如Moq或RhinoMocks)来完成此操作。

为了解释你如何简单地使用模拟,我将展示如何通过显式实现一个模拟对象对象来记录方法调用,然后测试它们。

E.g.

MockCommandBus : ICommandBus 
{ 
    ICommand PassedCommand { get; set; } 
    MetaData PassedMetaData { get; set; } 

    public void Send(ICommand command, MetaData metaData) 
    { 
     this.PassedCommand = command; 
     this.PassedMetaData = metaData; 
    }  
} 

然后你的测试用例看起来就像这样:

[TestCase] 
public void PostSendsCommandOnBus() 
{ 
    // ARRANGE 
    var mockCommandBus = new MockCommandBus(); 

    ICommand expectedCommand = <whatever you expect>; 
    MetaData expectedMetaData = <whatever you expect>; 

    // Code to construct your CommandModule with mockCommandBus. 

    // ACT 
    // Code to invoke the method being tested. 

    // ASSERT 
    Assert.AreEqual(expectedCommand, mockCommandBus.PassedCommand); 
    Assert.AreEqual(expectedMetaData , mockCommandBus.PassedMetaData); 

} 

警告:

请注意,这只是一个方法,它恰好完全适合单元测试你的要求这里。过度使用mock来测试与低级依赖关系的显式交互可能会导致开发非常脆弱的测试套件,这些测试套件正在测试底层实现而不是系统的行为。

相关问题