标签: moq

如何验证在Moq中没有调用该方法?

如何验证在Moq中未调用该方法?

它有像AssertWasNotCalled这样的东西吗?

更新:从3.0版开始,可以使用新语法:

mock.Verify(foo => foo.Execute("ping"), Times.Never());
Run Code Online (Sandbox Code Playgroud)

.net c# moq

439
推荐指数
5
解决办法
7万
查看次数

返回传递给方法的值

我在接口上有一个方法:

string DoSomething(string whatever);
Run Code Online (Sandbox Code Playgroud)

我想用MOQ模拟这个,以便它返回传入的内容 - 类似于:

_mock.Setup( theObject => theObject.DoSomething( It.IsAny<string>( ) ) )
   .Returns( [the parameter that was passed] ) ;
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

c# moq mocking

352
推荐指数
3
解决办法
11万
查看次数

我如何告诉Moq返回任务?

我有一个声明的界面

Task DoSomethingAsync();
Run Code Online (Sandbox Code Playgroud)

我正在使用MoqFramework进行测试:

[TestMethod()]
public async Task MyAsyncTest()
{
   Mock<ISomeInterface> mock = new Mock<ISomeInterface>();
   mock.Setup(arg => arg.DoSomethingAsync()).Callback(() => { <my code here> });
   ...
}
Run Code Online (Sandbox Code Playgroud)

然后在我的测试中我执行调用的代码await DoSomethingAsync().而且测试在这条线上失败了.我究竟做错了什么?

c# unit-testing moq task-parallel-library

291
推荐指数
3
解决办法
11万
查看次数

在Moq中分配/ ref参数

是否可以使用Moq(3.0+)分配out/ ref参数?

我看过使用Callback(),但Action<>不支持ref参数,因为它基于泛型.我也最好It.Isref参数的输入上放置一个约束(),尽管我可以在回调中做到这一点.

我知道Rhino Mocks支持这个功能,但我正在研究的项目已经在使用Moq了.

c# parameters moq ref out

268
推荐指数
7
解决办法
11万
查看次数

Moq第一次和第二次使用不同的返回值

我有这样的测试:

    [TestCase("~/page/myaction")]
    public void Page_With_Custom_Action(string path) {
        // Arrange
        var pathData = new Mock<IPathData>();
        var pageModel = new Mock<IPageModel>();
        var repository = new Mock<IPageRepository>();
        var mapper = new Mock<IControllerMapper>();
        var container = new Mock<IContainer>();

        container.Setup(x => x.GetInstance<IPageRepository>()).Returns(repository.Object);

        repository.Setup(x => x.GetPageByUrl<IPageModel>(path)).Returns(() => pageModel.Object);

        pathData.Setup(x => x.Action).Returns("myaction");
        pathData.Setup(x => x.Controller).Returns("page");

        var resolver = new DashboardPathResolver(pathData.Object, repository.Object, mapper.Object, container.Object);

        // Act
        var data = resolver.ResolvePath(path);

        // Assert
        Assert.NotNull(data);
        Assert.AreEqual("myaction", data.Action);
        Assert.AreEqual("page", data.Controller);
    }
Run Code Online (Sandbox Code Playgroud)

GetPageByUrl在我的dashboardpathresolver中运行两次,我如何告诉Moq第一次返回null并且pageModel.Ojbect第二次?

c# nunit unit-testing moq

232
推荐指数
6
解决办法
7万
查看次数

如何在ASP.Net MVC中模拟Controller上的请求?

我使用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)

asp.net-mvc unit-testing rhino-mocks moq mocking

169
推荐指数
6
解决办法
8万
查看次数

使用Moq模拟单元测试的异步方法

我正在测试一个进行Web API调用的服务的方法.HttpClient如果我还在本地运行Web服务(位于解决方案中的另一个项目中),则使用正常工作正常进行单元测试.

但是,当我签入我的更改时,构建服务器将无法访问Web服务,因此测试将失败.

我已经为我的单元测试设计了一种方法,通过创建一个IHttpClient接口并实现我在我的应用程序中使用的版本.对于单元测试,我使用模拟的异步post方法创建一个模拟版本.这是我遇到问题的地方.我想HttpStatusResult为这个特定的测试返回一个OK .对于另一个类似的测试,我将返回一个糟糕的结果.

测试将运行但永远不会完成.它挂在等待.我是异步编程,代表和Moq本身的新手,我一直在搜索SO和谷歌一段时间学习新东西,但我似乎仍然无法解决这个问题.

这是我试图测试的方法:

public async Task<bool> QueueNotificationAsync(IHttpClient client, Email email)
{
    // do stuff
    try
    {
        // The test hangs here, never returning
        HttpResponseMessage response = await client.PostAsync(uri, content);

        // more logic here
    }
    // more stuff
}
Run Code Online (Sandbox Code Playgroud)

这是我的单元测试方法:

[TestMethod]
public async Task QueueNotificationAsync_Completes_With_ValidEmail()
{
    Email email = new Email()
    {
        FromAddress = "bob@example.com",
        ToAddress = "bill@example.com",
        CCAddress = "brian@example.com",
        BCCAddress = "ben@example.com",
        Subject = "Hello",
        Body = "Hello …
Run Code Online (Sandbox Code Playgroud)

c# unit-testing asynchronous moq

163
推荐指数
4
解决办法
7万
查看次数

为什么我收到消息"非虚拟(在VB中可覆盖)成员上的无效设置..."?

我有一个单元测试,我必须模拟一个返回bool类型的非虚方法

public class XmlCupboardAccess
{
    public bool IsDataEntityInXmlCupboard(string dataId,
                                          out string nameInCupboard,
                                          out string refTypeInCupboard,
                                          string nameTemplate = null)
    {
        return IsDataEntityInXmlCupboard(_theDb, dataId, out nameInCupboard, out refTypeInCupboard, nameTemplate);
    }
}
Run Code Online (Sandbox Code Playgroud)

所以我有一个XmlCupboardAccess类的模拟对象,我试图在我的测试用例中为这个方法设置mock,如下所示

[TestMethod]
Public void Test()
{
    private string temp1;
    private string temp2;
    private Mock<XmlCupboardAccess> _xmlCupboardAccess = new Mock<XmlCupboardAccess>();
    _xmlCupboardAccess.Setup(x => x.IsDataEntityInXmlCupboard(It.IsAny<string>(), out temp1, out temp2, It.IsAny<string>())).Returns(false); 
    //exception is thrown by this line of code
}
Run Code Online (Sandbox Code Playgroud)

但是这条线引发了异常

Invalid setup on a non-virtual (overridable in VB) member: 
x => x.IsDataEntityInXmlCupboard(It.IsAny<String>(), …
Run Code Online (Sandbox Code Playgroud)

c# unit-testing moq

163
推荐指数
4
解决办法
13万
查看次数

使用Moq确定是否调用方法

我的理解是,如果我调用更高级别的方法,我可以测试是否会发生方法调用,即:

public abstract class SomeClass()
{    
    public void SomeMehod()
    {
        SomeOtherMethod();
    }

    internal abstract void SomeOtherMethod();
}
Run Code Online (Sandbox Code Playgroud)

我想测试一下,如果我打电话,SomeMethod()那么我希望它SomeOtherMethod()会被调用.

我认为这种测试可以在模拟框架中使用吗?

.net c# unit-testing moq mocking

153
推荐指数
2
解决办法
8万
查看次数

用Moq模拟扩展方法

我有一个预先存在的界面......

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)

c# extension-methods unit-testing moq mocking

153
推荐指数
6
解决办法
9万
查看次数