标签: moq

模拟 C# 中同一个类中的方法

我的代码是这样的 我试图模拟我在 GetUrlToSurveyMonkeyAuthentication 方法中使用的 htttputility urlencode 方法。

    //this is the method which uses urlencode method which is in the same class
    public string GetUrlToSurveyMonkeyAuthentication(string redirectUri, string clientId, string apiKey)
    {
        string urlToOauthSurveyMonkeyAuthentication = SurveyMonkeyBaseUrl + AuthCodeEndUrl + ParameterSeparator + ParameterRedirectUriName + UrlEncodes(redirectUri) + ParameterAdditioner + ParameterClientIdName + UrlEncodes(clientId) + ParameterAdditioner + ParameterResponseTypeName + UrlEncodes(ResponseType) + ParameterAdditioner + ParameterAPIKeyname + UrlEncodes(apiKey);
        return urlToOauthSurveyMonkeyAuthentication;
    }
    // my urlencode method which needs to be mocked it is in the same class SurveyMonkeyAPIService
    public …
Run Code Online (Sandbox Code Playgroud)

c# nunit unit-testing moq

1
推荐指数
1
解决办法
3513
查看次数

Moq 返回与参数相同的委托

我对 Moq 非常陌生,正在寻找一种能够模拟以下界面的方法。

public interface ICacheProveder
{
    T GetOrAddToCache<T>(string key, Func<T> populateFunc);
}
Run Code Online (Sandbox Code Playgroud)

该接口目前用于缓存代码表等项目。模拟需要返回任何传递到 via populateFunc 的结果。我目前使用的是 Moq 版本 4.2.1502.911

c# generics moq

1
推荐指数
1
解决办法
1765
查看次数

MOQ如果方法设置相交会发生什么?

如果您愿意,当两个设置相交或重叠时会发生什么.

例如,在下面的场景中,设置重叠,因为显然"aSpecificString"也被视为任何字符串.

Interface ISomeInterface
{
    int SomeMethod(string param);
}

[TestMethod]
public void SomeClass_ShouldBehaveProperly_GivenSomeScenario()
{
    var mock = new Mock<ISomeInterface>(MockBehavior.Strict);
    mock.Setup(m => m.SomeMethod("aSpecificString"))
        .Returns(100);
    mock.Setup(m => m.SomeMethod(It.IsAny<string>()))
        .Returns(0);

    /*the rest of the test*/
}
Run Code Online (Sandbox Code Playgroud)

我想知道它相交时会发生什么.

它会抛出异常还是无法检测到重叠并按照添加顺序使用第一个匹配设置?

我认为最好避免重叠设置.

c# unit-testing moq

1
推荐指数
1
解决办法
80
查看次数

如何使用Moq使用JSON主体创建模拟HTTP post请求

我正在尝试基本上做标题所说的为了对我的api控制器进行单元测试,但我找不到合适的方法并且无法承担花费太多时间.这是我的代码.

[TestMethod]
public void Should_return_a_valid_json_result()
{
    // Arrange
    Search search = new Search();
    search.Area = "test";
    string json = JsonConvert.SerializeObject(search);

    var context = new Mock<HttpContextBase>();
    var request = new Mock<HttpRequestBase>();

    request.Setup(r => r.HttpMethod).Returns("POST");
    request.Setup(r => r.InputStream.ToString()).Returns(json);

    context.Setup(c => c.Request).Returns(request.Object);

    var controller = new UserController();
    controller.ControllerContext = new HttpControllerContext() {  RequestContext = context };

   //more code

}
Run Code Online (Sandbox Code Playgroud)

最后一行返回错误CS0029无法将类型'Moq.Mock System.Web.HttpContextBase'隐式转换为'System.Web.Http.Controllers.HttpRequestContext'.

我也不确定我应该使用的Moq语法,其他问题,示例和Moq文档对我没什么帮助.

c# json unit-testing moq asp.net-web-api

1
推荐指数
2
解决办法
3204
查看次数

C# 模拟 Mock&lt;StreamWriter&gt;

我是 C# 模拟的新手,我正在尝试阅读一些代码,但其中一个测试失败了,您能否向我解释一下下面的源代码正在尝试测试什么以及它何时会失败?

Mock<StreamWriter> _streamWriterMock;
string[] expectedLines;
.
.
.
foreach (var line in expectedLines)
{
    _streamWriterMock.Verify(a => a.Write(line), Times.Exactly(1));
}
Run Code Online (Sandbox Code Playgroud)

c# unit-testing moq mocking

1
推荐指数
1
解决办法
3873
查看次数

UnitTests - Moq - 如何从与 Setup() 中的参数匹配的 Moq 返回() 对象

我对 Moq 感到困惑,我不确定这里有什么问题。

我想测试依赖于 ILeadStorageService 的 LeadService,并且我想以这种方式配置 Moq - 返回与安装程序中传递的 GUID 匹配的对象。

问题出在 Moq Setup/Returns 行中,因为当我将依赖对象替换为其真实实例时 - 测试通过,但完全错误。我不想只测试 LeadService,而不是从属存储。

    public LeadService( IConfigurationDbContext configurationDbContext, 
                        ILeadStorageService leadStorageService,
                        ILeadDeliveryService deliveryService)
    {
        this.configurationDbContext = configurationDbContext;
        this.leadStorageService = leadStorageService;
        this.deliveryService = deliveryService;

    }
Run Code Online (Sandbox Code Playgroud)

测试方法

        public TestLeadResponse ProcessTestLead(TestLeadRequest request)
        {
        var response = new TestLeadResponse()
        {
            Status = TestLeadStatus.Ok
        };

        try
        {
            var lead = leadStorageService.Get(request.LeadId);
            if (lead == null)
            {
                throw new LeadNotFoundException(request.LeadId);
            }

            var buyerContract =
                configurationDbContext.BuyerContracts.SingleOrDefault(bc => bc.Id == request.BuyerContractId);
            if (buyerContract == …
Run Code Online (Sandbox Code Playgroud)

c# unit-testing mstest moq

1
推荐指数
1
解决办法
2043
查看次数

使用Moq模拟接口时,方法会发生什么?

使用Moq模拟接口时,方法会发生什么?

假设我有一个接口ISomething,IoC映射到该类Something。然后在我的测试中,我这样做:var something = new Mock<ISomething>();

可以说该接口包含一个方法: string method();

现在,如果我在模拟实例上调用该方法something.method(),它将被映射到类Something的实现,还是仅返回void?Moq是否会尝试将接口与实现映射?

c# testing moq

1
推荐指数
1
解决办法
430
查看次数

使用Moq针对异步方法设置C#测试

我正在尝试使用Moq创建一组测试方法来覆盖外部依赖项。这些依赖项本质上是异步的,我遇到了一组依赖项,它们在等待时再也不会返回,因此我不确定我缺少什么。

测试本身非常简单。

[TestMethod]
public async Task UpdateItemAsync()
{
    var repository = GetRepository();
    var result = await repository.UpdateItemAsync("", new object());
    Assert.IsNotNull(result);
}
Run Code Online (Sandbox Code Playgroud)

GetRepository上面的方法是设置各种模拟对象的方法,包括在其上调用Setup的方法。

private static DocumentDbRepository<object> GetRepository()
{
    var client = new Mock<IDocumentClient>();
    var configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();

    client.Setup(m => m.ReplaceDocumentAsync(It.IsAny<Uri>(), It.IsAny<object>(), It.IsAny<RequestOptions>()))
        .Returns(() =>
        {
            return new Task<ResourceResponse<Document>>(() => new ResourceResponse<Document>());
        });

    var repository = new DocumentDbRepository<object>(configuration, client.Object);
    return repository;
}
Run Code Online (Sandbox Code Playgroud)

下面列出了要测试的代码,执行带有await的行时,它永远不会返回。

public async Task<T> UpdateItemAsync(string id, T item)
{
    var result = await Client.ReplaceDocumentAsync(UriFactory.CreateDocumentUri(DatabaseId, CollectionId, id), item);
    return …
Run Code Online (Sandbox Code Playgroud)

c# unit-testing moq async-await

1
推荐指数
1
解决办法
654
查看次数

Asp.Net MVC 5测试IoC +依赖注入

我正在尝试测试我的项目.我以前从未使用过测试,我开始学习我想要一个帮助,在最简单的情况下我想测试这个,public ActionResult Index()但我不知道如何注入这些依赖项.

控制器:

控制器:

public class WorkPlacesController : Controller
{
    private readonly IWorkPlaceService workPlaceService;

    public WorkPlacesController(IWorkPlaceService workPlaceService)
    {
        this.workPlaceService = workPlaceService;
    }
    // GET: WorkPlaces
    public ActionResult Index()
    {
        var workPlaces = workPlaceService.GetWorkPlaces(includedRelated:  
        true);

        return View(workPlaces);
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的服务

服务

public class WorkPlaceService : IWorkPlaceService
{
    private readonly IWorkPlaceRepository workPlacesRepository;
    private readonly IUnitOfWork unitOfWork;


    public WorkPlaceService(IWorkPlaceRepository workPlacesRepository, IUnitOfWork unitOfWork)
    {
        this.workPlacesRepository = workPlacesRepository;
        this.unitOfWork = unitOfWork;
    }
}

public interface IWorkPlaceService
{
    IEnumerable<WorkPlace> GetWorkPlaces(string workPlaceDescription = null, …
Run Code Online (Sandbox Code Playgroud)

c# asp.net unit-testing dependency-injection moq

1
推荐指数
1
解决办法
529
查看次数

无法将带有[]的索引应用于"Castle.Proxies.RangeProxy"类型的表达式

导致此异常的原因是什么?我试图Moq用来模拟一个Microsoft.Office.Interop.Excel.Range.我想在Range里面筑巢另一个嘲笑.但是当我尝试访问嵌套异常时,会抛出异常.

例外

无法将带有[]的索引应用于"Castle.Proxies.RangeProxy"类型的表达式

[TestMethod]
public void RangeProxyIndexTest()
{
    // creating first range
    var cell1 = new Moq.Mock<Range>();
    cell1.Setup(c => c.Value2).Returns("1");

    var range1Mock = new Moq.Mock<Range>();
    range1Mock.SetupGet(r => r[1, Moq.It.IsAny<Object>()]).Returns(cell1.Object);
    var range1 = range1Mock.Object;

    // creating second range
    var cell2 = new Moq.Mock<Range>();
    cell2.Setup(c => c.Value2).Returns("2");

    var range2Mock = new Moq.Mock<Range>();
    range2Mock.SetupGet(r => r[1, Moq.It.IsAny<Object>()]).Returns(cell2.Object);
    var range2 = range2Mock.Object;

    // merging both ranges into 1
    var range3Mock = new Moq.Mock<Range>();
    range3Mock.SetupGet(r => r[1, Moq.It.IsAny<Object>()]).Returns(range1); …
Run Code Online (Sandbox Code Playgroud)

c# excel unit-testing moq mocking

1
推荐指数
1
解决办法
130
查看次数