我有一个接口,其方法需要一个数组Foo:
public interface IBar {
  void doStuff(Foo[] arr);
}
Run Code Online (Sandbox Code Playgroud)
我正在使用Mockito来嘲笑这个界面,我想断言它doStuff()被调用了,但我不想验证传递了什么参数 - "不关心".
如何使用any()泛型方法编写以下代码,而不是anyObject()?
IBar bar = mock(IBar.class);
...
verify(bar).doStuff((Foo[]) anyObject());
Run Code Online (Sandbox Code Playgroud) 我正在尝试将单元测试添加到我构建的ASP.NET MVC应用程序中.在我的单元测试中,我使用以下代码:
[TestMethod]
public void IndexAction_Should_Return_View() {
    var controller = new MembershipController();
    controller.SetFakeControllerContext("TestUser");
    ...
}
Run Code Online (Sandbox Code Playgroud)
使用以下帮助程序来模拟控制器上下文:
public static class FakeControllerContext {
    public static HttpContextBase FakeHttpContext(string username) {
        var context = new Mock<HttpContextBase>();
        context.SetupGet(ctx => ctx.Request.IsAuthenticated).Returns(!string.IsNullOrEmpty(username));
        if (!string.IsNullOrEmpty(username))
            context.SetupGet(ctx => ctx.User.Identity).Returns(FakeIdentity.CreateIdentity(username));
        return context.Object;
    }
    public static void SetFakeControllerContext(this Controller controller, string username = null) {
        var httpContext = FakeHttpContext(username);
        var context = new ControllerContext(new RequestContext(httpContext, new RouteData()), controller);
        controller.ControllerContext = context;
    }
}
Run Code Online (Sandbox Code Playgroud)
此测试类继承自具有以下内容的基类:
[TestInitialize]
public void Init() {
    ...
} …Run Code Online (Sandbox Code Playgroud) 我使用ASP.Net MVC框架在C#中有一个控制器
public class HomeController:Controller{
  public ActionResult Index()
    {
      if (Request.IsAjaxRequest())
        { 
          //do some ajaxy stuff
        }
      return View("Index");
    }
}
Run Code Online (Sandbox Code Playgroud)
我得到了一些关于模拟的技巧,并希望用以下和RhinoMocks测试代码
var mocks = new MockRepository();
var mockedhttpContext = mocks.DynamicMock<HttpContextBase>();
var mockedHttpRequest = mocks.DynamicMock<HttpRequestBase>();
SetupResult.For(mockedhttpContext.Request).Return(mockedHttpRequest);
var controller = new HomeController();
controller.ControllerContext = new ControllerContext(mockedhttpContext, new RouteData(), controller);
var result = controller.Index() as ViewResult;
Assert.AreEqual("About", result.ViewName);
Run Code Online (Sandbox Code Playgroud)
但是我一直收到这个错误:
异常System.ArgumentNullException:System.ArgumentNullException:值不能为null.参数名称:System.Web.Mvc.AjaxRequestExtensions.IsAjaxRequest(HttpRequestBase请求)中的请求
由于Request控制器上的对象没有setter.我尝试使用以下答案中的推荐代码使此测试正常工作.
这使用了Moq而不是RhinoMocks,并且在使用Moq时我使用以下内容进行相同的测试:
var request = new Mock<HttpRequestBase>();
// Not working - IsAjaxRequest() is static extension method and cannot be mocked …Run Code Online (Sandbox Code Playgroud) 如何使用模拟测试以下代码(使用模拟,修补程序装饰器和Michael Foord的Mock框架提供的标记):
def testme(filepath):
    with open(filepath, 'r') as f:
        return f.read()
Run Code Online (Sandbox Code Playgroud) 我是单元测试的新手,我不断听到很多东西被抛出的"模拟对象".通俗地说,有人可以解释什么是模拟对象,以及在编写单元测试时它们通常用于什么?
我的理解是,如果我调用更高级别的方法,我可以测试是否会发生方法调用,即:
public abstract class SomeClass()
{    
    public void SomeMehod()
    {
        SomeOtherMethod();
    }
    internal abstract void SomeOtherMethod();
}
Run Code Online (Sandbox Code Playgroud)
我想测试一下,如果我打电话,SomeMethod()那么我希望它SomeOtherMethod()会被调用.
我认为这种测试可以在模拟框架中使用吗?
我有一个预先存在的界面......
public interface ISomeInterface
{
    void SomeMethod();
}
Run Code Online (Sandbox Code Playgroud)
并且我使用mixin扩展了这个表面...
public static class SomeInterfaceExtensions
{
    public static void AnotherMethod(this ISomeInterface someInterface)
    {
        // Implementation here
    }
}
Run Code Online (Sandbox Code Playgroud)
我有一个叫这个我要测试的课程...
public class Caller
{
    private readonly ISomeInterface someInterface;
    public Caller(ISomeInterface someInterface)
    {
        this.someInterface = someInterface;
    }
    public void Main()
    {
        someInterface.AnotherMethod();
    }
}
Run Code Online (Sandbox Code Playgroud)
和测试,我想模拟界面并验证对扩展方法的调用...
    [Test]
    public void Main_BasicCall_CallsAnotherMethod()
    {
        // Arrange
        var someInterfaceMock = new Mock<ISomeInterface>();
        someInterfaceMock.Setup(x => x.AnotherMethod()).Verifiable();
        var caller = new Caller(someInterfaceMock.Object);
        // Act
        caller.Main();
        // Assert
        someInterfaceMock.Verify();
    }
Run Code Online (Sandbox Code Playgroud)
然而,运行此测试会产生异常......
System.ArgumentException: …Run Code Online (Sandbox Code Playgroud) 这是一个简单的例子,说明了我的问题的关键:
var innerLib = require('./path/to/innerLib');
function underTest() {
    return innerLib.doComplexStuff();
}
module.exports = underTest;
Run Code Online (Sandbox Code Playgroud)
我正在尝试为此代码编写单元测试.如何在innerLib不require完全嘲笑函数的情况下模拟出对该函数的要求?
编辑:所以这是我试图模拟全局需求,并发现它甚至不会这样做:
var path = require('path'),
    vm = require('vm'),
    fs = require('fs'),
    indexPath = path.join(__dirname, './underTest');
var globalRequire = require;
require = function(name) {
    console.log('require: ' + name);
    switch(name) {
        case 'connect':
        case indexPath:
            return globalRequire(name);
            break;
    }
};
Run Code Online (Sandbox Code Playgroud)
问题是requireunderTest.js文件中的函数实际上没有被模拟出来.它仍然指向全球require功能.所以我似乎只能underTest.js在同一个文件中模拟我正在进行模拟的函数.如果我使用全局require来包含任何内容,即使在我重写本地副本之后,所需的文件仍将具有全局require引用.
我有myService使用myOtherService,它进行远程调用,返回promise:
angular.module('app.myService', ['app.myOtherService'])
  .factory('myService', [
    myOtherService,
    function(myOtherService) {
      function makeRemoteCall() {
        return myOtherService.makeRemoteCallReturningPromise();
      }
      return {
        makeRemoteCall: makeRemoteCall
      };      
    }
  ])
Run Code Online (Sandbox Code Playgroud)
为了进行单元测试myService我需要模拟myOtherService,这样它的myService方法返回一个promise.我是这样做的:
describe('Testing remote call returning promise', function() {
  var myService;
  var myOtherServiceMock = {};
  beforeEach(module('app.myService'));
  // I have to inject mock when calling module(),
  // and module() should come before any inject()
  beforeEach(module(function ($provide) {
    $provide.value('myOtherService', myOtherServiceMock);
  }));
  // However, in order to properly construct my mock
  // I need $q, which can …Run Code Online (Sandbox Code Playgroud) 我没有玩这个并且通常使用嘲讽,但我想知道这两者之间的差异以及何时使用犀牛模拟中的一个或另一个.
更新:
我也用Ayende的话来找到我的问题的答案:
存根和模拟之间的区别
 
您可以在本文中获得这些术语的实际定义:模拟不是存根.我想从Rhino Mocks的角度来关注差异.
模拟是一个我们可以设置期望的对象,它将验证预期的操作确实已经发生.存根是您用于传递给测试代码的对象.您可以设置它的期望,因此它会以某种方式起作用,但这些期望永远不会得到验证.存根的属性将自动表现为普通属性,您无法设置它们的期望.
如果要验证测试代码的行为,您将使用具有适当期望的模拟,并验证.如果您只想传递可能需要以某种方式执行的值,但不是此测试的焦点,则将使用存根.
重要信息:存根永远不会导致测试失败.
mocking ×10
unit-testing ×7
c# ×3
moq ×3
javascript ×2
rhino-mocks ×2
.net ×1
angularjs ×1
asp.net-mvc ×1
httpcontext ×1
jasmine ×1
java ×1
mockito ×1
node.js ×1
python ×1