小编Old*_*Fox的帖子

实体框架核心:记录单个数据库上下文实例的查询

使用EF Core(或任何ORM)我想跟踪ORM在我的软件中进行某些操作期间对数据库的查询次数.

我之前在Python下使用过SQLAlchemy,在这个堆栈上,这很容易设置.我通常有一个单元测试,它针对一个场景的查询数量,针对内存中的SQLite数据库进行断言.

现在我想使用EF Core做同样的事情,并查看了Logging文档.

在我的测试设置代码中,我按照文档说的那样做:

using (var db = new BloggingContext())
{
    var serviceProvider = db.GetInfrastructure<IServiceProvider>();
    var loggerFactory = serviceProvider.GetService<ILoggerFactory>();
    loggerFactory.AddProvider(new MyLoggerProvider());
}
Run Code Online (Sandbox Code Playgroud)

但我遇到的问题我怀疑是以下结果(也来自文档):

您只需要使用单个上下文实例注册记录器.注册后,它将用于同一AppDomain中上下文的所有其他实例.

我在测试中看到的问题表明我的记录器实现是在多个上下文中共享的(这与我阅读它们时的文档一致).并且因为a)我的测试运行器在并行运行测试并且b)我的整个测试套件创建了数百个db上下文 - 它不能很好地工作.

问题/问题:

  • 我想要的是什么?
  • 即我可以使用仅用于该db上下文实例的db上下文注册记录器吗?
  • 还有其他方法可以完成我想要做的事情吗?

c# logging unit-testing xunit entity-framework-core

23
推荐指数
3
解决办法
2万
查看次数

如何模拟Excel VSTO插件中的行?

我试图在Range一个新的行中放置一个模拟(包含值的单元格)Range.但是当我尝试从中访问特定元素时Range,会抛出异常.

我已经尝试了一切,有没有人知道我在这里做错了什么?

例外

消息:测试方法xxx.MockUtilsTest.MockRowsTest引发异常:Microsoft.CSharp.RuntimeBinder.RuntimeBinderException:无法将带有[]的索引应用于类型为"Castle.Proxies.RangeProxy"的表达式

测试

[TestMethod]
public void MockRowsTest()
{
    var row1 = MockUtils.MockCells("test_row_1", "test_row_1");
    var row2 = MockUtils.MockCells("test_row_2", "test_row_2");
    var range = MockUtils.MockRows(row1, row2);

    Assert.IsNotNull(range);
    Assert.AreEqual(2, range.Count);
    Assert.IsNotNull(range.Rows);
    Assert.AreEqual(2, range.Rows.Count);
    Assert.AreSame(row1, range.Rows[1].Cells[1]); // exception is thrown here
    Assert.AreSame(row2, range.Rows[2].Cells[1]);
    Assert.AreEqual("test_row_1", range.Rows[1].Cells[1].Value2);
    Assert.AreEqual("test_row_2", range.Rows[2].Cells[1].Value2);
}
Run Code Online (Sandbox Code Playgroud)

MockUtils

public static Range MockCellValue2(Object value)
{
    var cell = new Moq.Mock<Range>();
    cell.Setup(c => c.Value2).Returns(value);

    return cell.Object;
}

public static Range MockCells(params Object[] values)
{
    var cells = new …
Run Code Online (Sandbox Code Playgroud)

c# excel vsto unit-testing moq

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

gmock可以用于存根C函数吗?

我是gmock的新手,所以我想知道如何在单元测试的测试函数中调用简单的C函数.

例:

int func(int a)
{
  boolean find;
  // Some code
  find = func_1();
  return find;
}
Run Code Online (Sandbox Code Playgroud)

我搜索过gmock,在我的理解中gmock没有提供存根简单C函数的功能,因此我想问一下gmock是否提供了mock或stub的功能func_1

如果不是如何func_1在不更改源代码的情况下手动在我的测试代码中存根?我正在使用谷歌测试框架进行单元测试.

谢谢.

c unit-testing googletest gmock

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

如何moq实体框架SaveChangesAsync?

Mock<IDbContext> dbContext;

[TestFixtureSetUp]
public void SetupDbContext()
{
    dbContext = new Mock<IDbContext>();
    dbContext.Setup(c => c.SaveChanges()).Verifiable();
    dbContext.Setup(c => c.SaveChangesAsync()).Verifiable();
    dbContext.Setup(c => c.Customers.Add(It.IsAny<Customer>()))
             .Returns(It.IsAny<Customer>()).Verifiable();
}

[Test]
public async Task AddCustomerAsync()
{
    //Arrange
    var repository = new EntityFrameworkRepository(dbContext.Object);
    var customer = new Customer() { FirstName = "Larry", LastName = "Hughes" };

    //Act
    await repository.AddCustomerAsync(customer);

    //Assert
    dbContext.Verify(c => c.Customers.Add(It.IsAny<Customer>()));
    dbContext.Verify(c => c.SaveChangesAsync());
}

[Test]
public void AddCustomer()
{
    //Arrange
    var repository = new EntityFrameworkRepository(dbContext.Object);
    var customer = new Customer() { FirstName = "Larry", LastName = …
Run Code Online (Sandbox Code Playgroud)

c# unit-testing entity-framework moq async-await

10
推荐指数
2
解决办法
3090
查看次数

在setUp方法中报告Python unittest中的错误的正确方法是什么?

我已经对使用读了一些相互矛盾的意见assertsetUpPython的单元测试的方法.如果测试依赖的前提条件失败,我无法看到测试失败的危害.

例如:

import unittest

class MyProcessor():
    """
    This is the class under test
    """

    def __init__(self):
        pass

    def ProcessData(self, content):
        return ['some','processed','data','from','content'] # Imagine this could actually pass

class Test_test2(unittest.TestCase):

    def LoadContentFromTestFile(self):
        return None # Imagine this is actually doing something that could pass.

    def setUp(self):
        self.content = self.LoadContentFromTestFile()
        self.assertIsNotNone(self.content, "Failed to load test data")
        self.processor = MyProcessor()

    def test_ProcessData(self):
        results = self.processor.ProcessData(self.content)
        self.assertGreater(results, 0, "No results returned")

if __name__ == '__main__':
    unittest.main()
Run Code Online (Sandbox Code Playgroud)

这对我来说似乎是合理的事情,即确保测试能够运行.当由于设置条件而失败时,我们得到:

F
====================================================================== …
Run Code Online (Sandbox Code Playgroud)

python testing unit-testing assert arrange-act-assert

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

NUnit TestFixure和SetUp的嵌套TransactionScope

我派生自这个基类,以便将每个单独的测试封装到一个回滚的事务中

public abstract class TransactionBackedTest
{
    private TransactionScope _transactionScope;

    [SetUp]
    public void TransactionSetUp()
    {
        var transactionOptions = new TransactionOptions
        {
            IsolationLevel = IsolationLevel.ReadCommitted,
            Timeout = TransactionManager.MaximumTimeout
        };

        _transactionScope = new TransactionScope(TransactionScopeOption.Required, 
                                                 transactionOptions);
    }

    [TearDown]
    public void TransactionTearDown()
    {
        _transactionScope.Dispose();
    }
}
Run Code Online (Sandbox Code Playgroud)

使用这个我也尝试以相同的方式设置TestFixure事务:

[TestFixture]
class Example: TransactionBackedTest
{

    private TransactionScope _transactionScopeFixure;


    [TestFixtureSetUp]
    public void Init()
    {
        var transactionOptions = new TransactionOptions
        {
            IsolationLevel = IsolationLevel.ReadCommitted,
            Timeout = TransactionManager.MaximumTimeout
        };

        _transactionScopeFixure = new TransactionScope(TransactionScopeOption.Required,
                                                       transactionOptions);


        SetupAllDataForAllTest();
    }

    [TestFixtureTearDown]
    public void FixtureTearDown()
    { …
Run Code Online (Sandbox Code Playgroud)

c# sql nunit unit-testing transactions

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

与Moq嘲笑代表

我有一个界面:

public interface IRepeater
{
    void Each(string path, Action<string> action);
}
Run Code Online (Sandbox Code Playgroud)

我想用这个模拟这个界面Moq.现在我可以做到以下几点:

var mock = new Mock<IRepeater>();
mock.Setup(m => m.Each(It.IsAny<string>(), It.IsAny<Action<string>>());
Run Code Online (Sandbox Code Playgroud)

但是,为了帮助测试,我希望能够模拟将string其传递给Action<string>.可以这样做Moq吗?如果有,怎么样?

更新

澄清我正在测试class一个依赖于它的不同的东西IRepeater.我想嘲笑IRepeater.Each,所以我可以控制stringAction得到,所以我可以测试的行为.

所以如果我有class这样的话.

public class Service
{
    private readonly IRepeater _repeater;

    public Service(IRepeater repeater)
    {
        _repeater = repeater;
    }

    public string Parse(string path)
    {
        var builder = new StringBuilder();

        _repeater.Each(path, line => builder.Append(line));

        return builder.ToString();
    }
} …
Run Code Online (Sandbox Code Playgroud)

c# unit-testing moq mocking

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

如何模拟IDataReader来测试将SqlDataReader转换为System.DataView的方法

我是Moq的新手,我正在努力编写单元测试来测试转换SqlDataAdapter为的方法System.DataView.这是我的方法:

private DataView ResolveDataReader(IDataReader dataReader)
{
    DataTable table = new DataTable();

    for (int count = 0; count < dataReader.FieldCount; count++)
    {
        DataColumn col = new DataColumn(dataReader.GetName(count), 
                                        dataReader.GetFieldType(count));
        table.Columns.Add(col);
    }

    while (dataReader.Read())
    {
        DataRow dr = table.NewRow();
        for (int i = 0; i < dataReader.FieldCount; i++)
        {
            dr[i] = dataReader.GetValue(dataReader.GetOrdinal(dataReader.GetName(i)));
        }
        table.Rows.Add(dr);
    }

    return table.DefaultView;
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试创建以创建类似于:

var dataReaderMock = new Mock<IDataReader>();
var records = new Mock<IDataRecord>();
dataReaderMock.Setup(x => x.FieldCount).Returns(2);
dataReaderMock.Setup(x => x.Read()).Returns(() => records);
Run Code Online (Sandbox Code Playgroud)

我想传递一些数据并验证它是否已转换.

谢谢.

c# unit-testing moq mocking idatareader

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

起订量。模拟委托输入

我正在尝试使用 Moq 来模拟代表,但到目前为止我所做的一切都是徒劳的。我做了一个小例子来说明如何设置:

1.代理类正在抽象WCF服务

public interface IServiceProxy
{
    void FooService(ServiceProxy.FooServiceDelegate service);
}

public class ServiceProxy : IServiceProxy
{
    private readonly EndpointAddress _fooServiceEndpoint;

    public ServiceProxy(IConfiguration configuration)
    {
        _fooServiceEndpoint = new EndpointAddress(new Uri(configuration.WcfServiceEndpoint));
    }

    public delegate void FooServiceDelegate(IFooBar proxy);


    public void FooService(FooServiceDelegate service)
    {
        Do<IFooBar>((service.Invoke), _fooServiceEndpoint);
    }


    private void Do<T>(UseServiceDelegate<T> f, EndpointAddress address)
    {
        UsingService<T>.Use(f.Invoke, address);
    }
}
Run Code Online (Sandbox Code Playgroud)

2.服务定义

/// <summary>
/// This is the interface the WCF service exposes
/// </summary>
public interface IFooBar
{
    string Hello(string name);
}
Run Code Online (Sandbox Code Playgroud)

3.以及使用代理的类

public …
Run Code Online (Sandbox Code Playgroud)

c# delegates unit-testing moq mocking

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

Verify() 和 Setup()...VerifyAll() 之间的最小起订量差异

我正在创建几个单元测试,我想验证是否使用我期望的属性调用方法。

因此,鉴于这个非常简单的系统:

public class Employee
{
    public bool IsEmployed { get; set; }
}

public class DataStore
{
    public void UpdateEmployee(Employee obj)
    {
        // Save in DB
    }
}

public interface IDataStore
{
    void UpdateEmployee(Employee employee);
}

public Employee FireEmployee(IDataStore dataStore, Employee employee)
{
    employee.IsEmployed = false;

    dataStore.UpdateEmployee(employee);

    return employee;
}
Run Code Online (Sandbox Code Playgroud)

我想验证该DataStore.UpdateEmployee()方法是否在Employee.IsEmployed属性设置为 false时被调用。所以这里有两个测试用例,我认为它们应该完成同样的事情。

[Test]
public void TestViaVerify()
{
    //Arrange
    Mock<IDataStore> dataStore = new Mock<IDataStore>();
    var robert = new Employee { IsEmployed = true };

    //Act
    FireEmployee(dataStore.Object, …
Run Code Online (Sandbox Code Playgroud)

c# nunit unit-testing assert moq

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