Tag: unit testing模拟

Moq并抛出一个SqlException

我有以下代码来测试,当某个名称传递给我的方法时,它会抛出一个SQLexception(有理由那个,虽然听起来有点奇怪)。 mockAccountDAL.Setup(m => m.CreateAccount(It.IsAny(), “Display Name 2”, It.IsAny())).Throws(); 但是,这不会编译,因为SqlException的构造函数是内部的: ‘System.Data.SqlClient.SqlException’必须是具有公共无参数构造函数的非抽象类型,以便在generics类型或方法’Moq.Language.IThrows.Throws()’中将其用作参数’TException’ 现在,我可以更改它以声明它应该抛出Exception ,但这对我不起作用,因为我的方法应该返回一个状态代码,如果它是一个SqlException而另一个是任何其他exception。 这就是我的unit testing正在测试的内容。 有没有办法实现这一点,既没有改变我正在测试的方法的逻辑,或没有测试这种情况?

使用Mock IDbSet对Entity Framework进行unit testing

我以前从来没有真正完成过unit testing,而且在第一次测试时我遇到了绊倒和绊倒。 问题是_repository.Golfers.Count(); 始终表示DbSet为空。 我的测试很简单,我只想添加一个新的高尔夫球手 [TestClass] public class GolferUnitTest //: GolferTestBase { public MockGolfEntities _repository; [TestMethod] public void ShouldAddNewGolferToRepository() { _repository = new MockGolfEntities(); _repository.Golfers = new InMemoryDbSet(CreateFakeGolfers()); int count = _repository.Golfers.Count(); _repository.Golfers.Add(_newGolfer); Assert.IsTrue(_repository.Golfers.Count() == count + 1); } private Golfer _newGolfer = new Golfer() { Index = 8, Guid = System.Guid.NewGuid(), FirstName = “Jonas”, […]

如何在unit testing中moq一个NetworkStream?

我正在使用Moq和NUnit作为unit testing框架。 我编写了一个方法,给出了一个NetworkStream对象作为参数: public static void ReadDataIntoBuffer(NetworkStream networkStream, Queue dataBuffer) { if ((networkStream != null) && (dataBuffer != null)) { while (networkStream.DataAvailable) { byte[] tempBuffer = new byte[512]; // read the data from the network stream into the temporary buffer Int32 numberOfBytesRead = networkStream.Read(tempBuffer, 0, 512); // move all data into the main buffer for […]

模拟不是接口的类

我一直在编写一些从providerbase类inheritance的c#中的提供程序。 我发现很难编写使用提供程序的测试,因为大多数模拟框架只允许你模拟一个接口。 有没有办法模拟对从providerbaseinheritance的提供程序的调用? 如果没有,是否有一种模式可以用来实现提供者的模拟?

Moq Params TargetParameterCountException:参数计数不匹配exception

以下是我的通用基础存储库接口 public interface IRepository { IQueryable AllIncluding(params Expression<Func>[] includeProperties); } 我的实体 public class Sdk { public Sdk() { this.Identifier = Guid.NewGuid().ToString(); } public virtual ICollection AccessibleResources { get; set; } public string Identifier { get; set; } } 以下是具体的回购 public interface ISdkRepository : IRepository { } 现在我正在尝试使用moq测试控制器 以下是我试图测试的代码 public ActionResult GetResources(string clientId) { var sdkObject […]