Tag: unit testing

如何让NUnit TestProject在运行时使用自己的配置?

是否可以让Resharper(或NUnit?)知道我希望每个测试在其自己的项目下查找App.config ,即使在一起运行解决方案中的所有测试时也是如此? 背景: 我正在使用NUnit和Resharper附带的测试运行器,我在同一个解决方案中有几个测试项目。 我的一些测试依赖于位于各自项目下的配置文件。 当我自己运行一个测试项目时,它将使用它的内部App.config ,一切正常。 当我尝试在解决方案中run all tests in current test session ,或者使用快捷方式run all tests in current test session时,将不会选择任何配置文件,并且默认情况下,任何取决于配置的测试都将失败。 出于这个原因,我通常首先在解决方案中运行所有测试,然后右键单击test-runner中的每个配置相关项目中的节点,然后单独运行它们。

断言比较两个对象列表C#

我目前正在尝试学习如何使用unit testing,并且我已经创建了3个动物对象的实际列表以及3个动物对象的预期列表。 问题是我如何断言检查列表是否相等? 我尝试过CollectionAssert.AreEqual和Assert.AreEqual,但无济于事。 任何帮助,将不胜感激。 测试方法: [TestMethod] public void createAnimalsTest2() { animalHandler animalHandler = new animalHandler(); // arrange List expected = new List(); Animal dog = new Dog(“”,0); Animal cat = new Cat(“”,0); Animal mouse = new Mouse(“”,0); expected.Add(dog); expected.Add(cat); expected.Add(mouse); //actual List actual = animalHandler.createAnimals(“”,””,””,0,0,0); //assert //this is the line that does not evaluate […]

使用Moq模拟OpenXML

我应该如何测试以下GetWorksheetPart方法: public class ExcelDocument : IExcelDocument { private readonly string _filePath; public ExcelDocument(string filePath) { _filePath = filePath; } public WorksheetPart GetWorksheetPart(ISpreadsheetDocument excelDoc, string sheetName) { Sheet sheet = excelDoc.GetSheet(sheetName); if (sheet == null) { throw new ArgumentException( String.Format(“No sheet named {0} found in spreadsheet {1}”, sheetName, _filePath), “sheetName”); } return excelDoc.GetPartById(sheet.Id); } } IExcelDocument和包装器的SpreadsheetDocumentWrapper接口是: […]

如何对依赖于Console的switch语句进行unit testing

我是unit testing的新手,我正在使用VS 2010unit testing框架。 我有一个函数可以从用户那里获取一个整数,然后根据用户输入执行不同的函数。 我已经阅读了很多unit testing,但是我没有找到任何能告诉我如何测试switch语句的每个分支的东西。 到目前为止我得到了什么: [TestMethod] public void RunBankApplication_Case1() { using (var sw = new StringWriter()) { using (var sr = new StringReader(“1”)) { Console.SetOut(sw); Console.SetIn(sr); BankManager newB = new BankManager(); newB.RunBankApplication(); var result = sw.ToString(); string expected = “Enter Account Number: “; Assert.IsTrue(result.Contains(expected)); } } } 当调用案例1下的函数时,首先发生的是字符串“输入帐号:”被写入控制台。 但是,这根本不起作用。 我没有正确地将输入传递给控制台吗? 谢谢您的帮助! 编辑:我的RunBankApplication()函数: […]

使用Moq的unit testing工作单元和通用存储库模式框架

我正在使用Moq对使用工作单元和通用存储库的服务进行unit testing。 问题是在服务类中,当我在调试模式下运行测试时,_subsiteRepository始终为null。 我正在嘲笑服务类的设置 private readonly IRepository _subsiteRepository; public PlatformService(IUnitOfWork unitOfWork) { _subsiteRepository = unitOfWork.GetRepository(); } 以及正在测试的这个类中的方法。 问题是_subsiteRepository始终为null。 该方法不仅仅是这个,但这是相关的部分。 public async Task<IEnumerable> GetSubsites() { // Get Subsites var subsites = await _subsiteRepository .GetAll() .ToListAsync(); } 最后这是我正在运行的测试: private readonly Mock<IRepository> _subsiteRepository; private readonly Mock<IUnitOfWork> _unitOfWork; private readonly PlatformService _platformService; _subsiteRepository = new Mock<IRepository>(); _unitOfWork = new […]

c# – 使用OR条件断言

我正在检查三个字符的字符串 Assert.AreEqual(myString.Substring(3,3), “DEF”, “Failed as DEF was not observed”); 事情在这里它可以是DEF或RES ,现在处理这个我能想到的是以下 bool check = false; if( myString.Substring(3,3) == “DEF” || myString.Substring(3,3) == “RED” ) check = true; Assert.IsTrue(check,”Failed”); Console.WriteLine(“”Passed); 有一种方法我可以在Assert中使用一些OR事物 ps我正在编写unit testing,是的,我将使用三元运算符代替….

创建IEqualityComparer <IEnumerable >

我正在使用xUnit,如果T是自定义类型,它无法确定2 IEnumerable是否相等。 我已经尝试过使用LINQ SequenceEqual但是由于T的实例不同,所以返回false; 这是一个使用非工作IEqualityComparer的基本测试 [Fact] public void FactMethodName() { var one = new[] { new KeywordSchedule() { Id = 1 } }; var two = new[] { new KeywordSchedule() { Id = 1 } }; Assert.Equal(one, two, new KeywordScheduleComparer()); } public class KeywordScheduleComparer : IEqualityComparer<IEnumerable> { public bool Equals(IEnumerable x, IEnumerable y) { return […]

在此示例中,Microsoft是否有权在每个测试中执行多个断言?

最近我一直在努力改进我的unit testing,并且真正让我感到困惑的UT的“规则”之一是“每次测试的一个断言”。 我很想知道人们是否认为MS在断言这个测试方面做了正确的事情(忽略缺乏模拟等)。 根据我目前的理解,这个例子应该真正执行一个需要测试的每个对象属性的创建调用(而不是一个调用和多个断言)。 我是否正确地做出这个假设? 方法取自: http : //msdn.microsoft.com/en-us/vs2010trainingcourse_aspnetmvc3testing_topic4 [TestMethod()] [DeploymentItem(“MvcMusicStore.mdf”)] [DeploymentItem(“MvcMusicStore_log.ldf”)] public void CreateTest() { using (TransactionScope ts = new TransactionScope()) { StoreManagerController target = new StoreManagerController(); Album album = new Album() { GenreId = 1, ArtistId = 1, Title = “New Album”, Price = 10, AlbumArtUrl = “/Content/Images/placeholder.gif” }; ActionResult actual; actual = […]

在nhibernate中缺少对环境事务的支持?

我知道NHibernate支持环境事务,因为NHibernate会话在事务范围内的环境事务中登记。 但是,有一些奇怪之处,请考虑以下测试: [Test] public void Transaction_RollsBackTransactionInsideOfAmbientTransaction_AmbientTransactionAborted() { // arrange ISessionFactory sessionFactory = SessionFactoryOneTimeInitializer.GetTestSessionFactory(); ISession session = sessionFactory.OpenSession(); SessionFactoryOneTimeInitializer.CreateDataBaseSchemaIfRequiredByConfiguration(session); using (new TransactionScope()) { using (ITransaction transaction = session.BeginTransaction()) { // act transaction.Rollback(); } // assert Assert.AreEqual(TransactionStatus.Aborted, Transaction.Current.TransactionInformation.Status); } } 此测试失败。 NHibernate将如何确保环境事务不会持久存储到数据库?

AspNetCore上的unit testing控制器模型validation

在ASPNET核心项目中,我正在尝试创建一些unit testing,以validation我的数据validation逻辑是否正常工作。 我的控制器非常简单: [HttpPost] [Route(“Track”)] public void Track([FromBody] DataItem item) { if (!ModelState.IsValid) throw new ArgumentException(“Bad request”); _dataItemSaver.SaveData(item); } 我正在使用一个测试基类,它将_myController对象设置为测试中的控制器。 public ControllerTestBase() { var builder = new ConfigurationBuilder() .AddJsonFile(“appsettings.json”, optional: false, reloadOnChange: true) .AddJsonFile($”buildversion.json”, optional: true) .AddEnvironmentVariables(); _config = builder.Build(); var services = new ServiceCollection() .AddEntityFrameworkInMemoryDatabase() .AddDbContext(options => { options.UseInMemoryDatabase(); }) .AddScoped() .AddScoped() .Configure(_config.GetSection(nameof(MyConfig))); services […]