CustomerRepository.GetCustomers()
方法内的代码执行两次。为什么会这样呢?在图片中,我展示了在方法内部执行代码的步骤。
描述。该代码进入步骤“ 5”。在步骤“ 5”之后,代码转到步骤“ 6”。在步骤“ 11”之后,调试器根据代码继续工作。
Program.cs
using System.Threading.Tasks;
namespace ConsoleAppCore
{
class Program
{
static async Task Main(string[] args) // ++
{
// await TestMain();
Test1 test1 = new Test1();
await test1.TestMain();
}
}
}
Test1.cs
using System.Threading.Tasks;
//
using NUnit.Framework;
using Microsoft.VisualStudio.TestTools.UnitTesting;
//
using ConsoleApp;
using ConsoleApp.Model;
using DBRepository.Interfaces;
using DBRepository.Repositories;
using DBRepository.Factories;
namespace ConsoleAppCore
{
// NUnit тестирование
// пишем классы с атрибутом [TestFixture]
// пишем методы с атрибутом [Test]
[TestFixture]
public class Test1
{
public Test1()
{
TestMain();
}
public Task TestMain()
{
return GetCustomersTest_1();
}
/// <summary>
/// ____
/// </summary>
[TestMethod]
public async Task GetCustomersTest_1()
{
SettingsService settingsService = new SettingsService();
Settings settings = new Settings();
// Получить строку подключения
settings = settingsService.ReadFilfeT();
string connectionString = settings.ConnectionString;
IRepositoryContextFactory _iRepositoryContextFactory = new RepositoryContextFactory();
ICustomerRepository _iCustomerRepository = new CustomerRepository(connectionString, _iRepositoryContextFactory);
var customerList = await _iCustomerRepository.GetCustomers();
string strTest = "";
}
}
CustomerRepository.cs
using DBRepository.Interfaces;
using Models;
//
using System.Threading.Tasks;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
namespace DBRepository.Repositories
{
public class CustomerRepository : BaseRepository, ICustomerRepository
{
// Constructor
public CustomerRepository(string connectionString, IRepositoryContextFactory contextFactory) : base(connectionString, contextFactory)
{
}
public async Task<List<Customer>> GetCustomers()
{
using (var context = ContextFactory.CreateDbContext(ConnectionString))
{
var query = context.Customers.AsQueryable();
query = query.Where(p => p.ContactName.Contains("Maria"));
return await query.ToListAsync();
}
}
}
}
问题出在您的测试代码中。您正在从TestMain
执行两次Program.cs
。注意,Test1
构造函数已经在内部调用了TestMain
方法。完成之后,您再手动调用一次。假设您手动调用了一次TestMain
,则无需从Test1
构造函数中调用它:
[TestFixture]
public class Test1
{
public Test1()
{
// Commenting this out.
//TestMain();
}
public Task TestMain()
{
return GetCustomersTest_1();
}
//...
希望这会有所帮助