小编tju*_*ugg的帖子

在单元测试中模拟HttpClient

我有一些问题试图包装我的代码用于单元测试.问题是这样的.我有接口IHttpHandler:

public interface IHttpHandler
{
    HttpClient client { get; }
}
Run Code Online (Sandbox Code Playgroud)

而使用它的类,HttpHandler:

public class HttpHandler : IHttpHandler
{
    public HttpClient client
    {
        get
        {
            return new HttpClient();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后是Connection类,它使用simpleIOC来注入客户端实现:

public class Connection
{
    private IHttpHandler _httpClient;

    public Connection(IHttpHandler httpClient)
    {
        _httpClient = httpClient;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后我有一个单元测试项目,有这个类:

private IHttpHandler _httpClient;

[TestMethod]
public void TestMockConnection()
{
    var client = new Connection(_httpClient);

    client.doSomething();  

    // Here I want to somehow create a mock instance of the http client
    // Instead of the …
Run Code Online (Sandbox Code Playgroud)

c# unit-testing moq

90
推荐指数
15
解决办法
7万
查看次数

使用 moq 设置一个方法来返回一个对象列表但得到 null

我一直在我的个人项目中进行测试并遇到了这个小问题。我有一个创建对象列表的测试方法,我设置了一个我在我测试的方法中使用的服务以返回模拟列表。但是,由于某种原因,设置无法正常工作并且返回 null。

下面是测试方法:

var mockList = new List<IBillItem>
{
    new BillItem
    {
        Id = 0,
        DueDate = new DateTime(),
        Name = "",
        IndexNumber = "",
        AccountNumber = "",
        Amount = decimal.One
    },
    new BillItem
    {
        Id = 0,
        DueDate = new DateTime(),
        Name = "",
        IndexNumber = "",
        AccountNumber = "",
        Amount = decimal.One
    }
};

_billHandlingService.Setup(x => x.GetAllBillsAsync(It.IsAny<string>())).Returns(Task.FromResult(mockList));

var listBillsVm = new ListBillsViewModel(new LoggerFactory(), _billHandlingService.Object, _settingsService.Object);

await listBillsVm.GetBillsAsync();

_billHandlingService.Verify(x => x.GetAllBillsAsync(_settingsService.Name), Times.AtMostOnce);

Assert.AreEqual(1, listBillsVm.BillsList.Count);
Run Code Online (Sandbox Code Playgroud)

这是具体类 im 测试的代码:

public async …
Run Code Online (Sandbox Code Playgroud)

c# unit-testing moq async-await

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

标签 统计

c# ×2

moq ×2

unit-testing ×2

async-await ×1