鉴于此类:
public class MyClass
{
private void MyMethod()
{
//...
}
public void Execute()
{
try
{
//...
MyMethod();
//...
}
catch(Exception e)
{
...
}
}
}
Run Code Online (Sandbox Code Playgroud)
我怎么能模拟MyMethod扔一个OutOfmemoryException?
编辑1:
鉴于MyMethod从数据库加载一些数据的下一种情况,以及发生一些不可预测的错误,MyMethod将引发异常.我希望能够对这种情况进行单元测试.在我的例子中,execute方法的catch子句.
[使用Moq]
我试图模拟一个具体的类并模拟该类的虚拟方法"Get()".在测试方法"GetItemsNotNull()"时,我总是返回null,而不是返回模拟函数.
这是代码
//SomeClasses.cs
namespace MoQExamples
{
public abstract class Entity
{
}
public class Abc : Entity
{
}
public interface IRepository<T> where T : Entity
{
IQueryable<T> Get();
}
public class Repository<T> : IRepository<T> where T : Entity
{
private readonly ISession _session;
public Repository()
{
_session = null;
}
public Repository(ISession session)
{
_session = session;
}
protected ISession CurrentSession
{
get { return _session; }
}
public virtual IQueryable<T> Get()
{
return CurrentSession.Query<T>();
}
}
public …Run Code Online (Sandbox Code Playgroud) 我有一个方法,它接受一个IList<Person>并返回一个IEnumberable如下:
internal static IEnumerable<Dictionary<string, string>> GetPersonsPerSite(IList<Person> Data)
{
//Implementation ...
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试创建一个模拟对象,IList<Person>所以我可以测试这个方法.
使用Moq我写了以下内容:
var mockObjects = new Mock<IList<Person>>();
mockObjects.Setup(x => x[0]).Returns(new Person()
{
SITE_ID = "test",
MPAN = "test",
ADDLINE1 = "test",
ADDLINE2 = "test",
ADDRESS_LINE_1 = "test",
ADDRESS_LINE_2 = "test"
});
Run Code Online (Sandbox Code Playgroud)
但是,当我来使用IEnumerable返回的对象时,抛出异常 Object reference not set to an instance of an object.
我是Moq的新手,我很确定我在这里缺少一个基本概念,但是我已经成功地能够使用其他模拟对象抛出异常和修改输出.
如果有人能指出我正确的方向,我会很感激.
我正在开始一个维护项目,我需要使用遗留代码并创建新代码.新的我可以创建适当的基于接口的开发,我可以使用Moq进行适当的单元测试.我不能将Moq用于遗留代码,因为他们没有适当的编码来模拟对象.根据阅读,Typemock看起来非常合适,因为我可以隔离对象并在遗留对象上调用方法时返回我们想要的内容.我非常喜欢简单易用的开发.我想知道是否有任何其他工具像Typemock我应该在承诺之前看一下,因为我必须付钱.
谢谢
PS:我们的是微软商店,我们使用C#/ ASP/ASp.Net/Silverlight和VB.Net
**我刚刚发现Infragistics也有一个模拟工具.
我在嘲笑我的控制器方法,我的控制器看起来像这样
我的控制器:
public class PController : BaseController
{
readonly IRFacade _repository;
public PController()
{
_repository = new RiFacade();
}
[CLSCompliant(false)]
public PController(IRFacade repositories)
{
if (repositories == null) throw new ArgumentNullException("repositories");
_repository = repositories;
}
public aMethod(String Id){
int[] arraynum = convert id to int[]
int numberthis = _repository.ActionFunction(arraynum);
..return stuff
}
Run Code Online (Sandbox Code Playgroud)
IRFacade我创建的界面看起来像这样
public interface IRFacade
{
int ActionFunction(int[] arrayOfNum);
}
Run Code Online (Sandbox Code Playgroud)
当我测试aMethod并且我必须模拟时,_repository我就像这样设置
var MockFacade = new Mock<IRFacade>();
// here fakeinput is a int[] varaible and …Run Code Online (Sandbox Code Playgroud) 我想模拟下面的代码行(通过MOQ在C#,MVC中): -
CustomerDto target = CustomerService.GetAllCustomer().FirstOrDefault(n => n.CustomerID == customer.CustomerID);
Run Code Online (Sandbox Code Playgroud)
其中CustomerService.GetAllCustomer()函数是控制器方法中的依赖项.
它在哪里使用FirstOrDefault()函数.在单元测试中,我不知道如何模拟它.
任何人都可以建议我这样做吗?
我有一个简单的抽象工厂,返回一个简单的类型.基本上,它只是用数据填充类型并返回它,类似于DTO.
public interface IPagingInstructionFactory
{
IPagingInstruction Create(int skip, int take, IProvider provider);
}
public interface IPagingInstruction
{
int Skip { get; }
int Take { get; }
IProvider Provider { get; }
}
Run Code Online (Sandbox Code Playgroud)
我现在想要创建一个模拟工厂,它基本上与真实工厂做同样的事情 - 它从Create()方法传递参数并从IPagingInstruction实例的属性返回它们.
这是一个有效的例子:
var pagingInstructionFactory = new Mock<IPagingInstructionFactory>();
pagingInstructionFactory
.Setup(x => x.Create(It.IsAny<int>(), It.IsAny<int>(), It.IsAny<IProvider>()))
.Returns((int skip, int take, IProvider provider) =>
new FakePagingInstruction(skip, take, provider));
public class FakePagingInstruction
: IPagingInstruction
{
public FakePagingInstruction(
int skip,
int take,
IProvider provider
)
{
if (provider == null)
throw …Run Code Online (Sandbox Code Playgroud) 这是我的类的最小复制,它通过Nest 1.7处理与Elasticsearch的通信:
public class PeopleRepository
{
private IElasticClient client;
public PeopleRepository(IElasticClient client)
{
this.client = client;
}
public Person Get(string id)
{
var getResponse = client.Get<Person>(p => p.Id(id));
// Want to test-drive this change:
if (getResponse.Source == null) throw new Exception("Person was not found for id: " + id);
return getResponse.Source;
}
}
Run Code Online (Sandbox Code Playgroud)
如代码中所述,我正在尝试测试某些更改。我正在以以下方式使用NUnit 2.6.4和Moq 4.2尝试执行此操作:
[Test]
public void RetrieveProduct_WhenDocNotFoundInElastic_ThrowsException()
{
var clientMock = new Mock<IElasticClient>();
var getSelectorMock = It.IsAny<Func<GetDescriptor<Person>, GetDescriptor<Person>>>();
var getRetvalMock = new Mock<IGetResponse<Person>>();
getRetvalMock
.Setup(r => r.Source) …Run Code Online (Sandbox Code Playgroud) 我Moq用来模拟一些界面.这里是:
var titleGenerator = new Mock<ITitleGenerator>();
titleGenerator.Setup(t => t.GenerateTitle()).Returns(Guid.NewGuid().ToString);
Console.WriteLine(titleGenerator.Object.GenerateTitle());
Console.WriteLine(titleGenerator.Object.GenerateTitle());
Run Code Online (Sandbox Code Playgroud)
它打印两次相同的值.但如果我用这个替换第二行:
titleGenerator.Setup(t => t.GenerateTitle()).Returns(() => Guid.NewGuid().ToString());
Run Code Online (Sandbox Code Playgroud)
它会在每次调用时返回唯一值.
我一直以为方法组只是lambda表达式的快捷方式.有什么区别吗?我试着在文档中搜索任何解释.有人可以开导我吗?
它看起来像方法组一次评估表达式并以某种方式缓存它?或者它有什么关系Moq?
我正在尝试测试我的服务的删除方法,为此我尝试首先将项目添加到存储库.但是,我不认为我的模拟存储库添加方法被调用,因为_mockRepository.Object.GetAll()它始终为null.我试过插入调试器,它也只是跳过它.我究竟做错了什么?
public class CommentServiceTest
{
private Mock<IRepository<Comment>> _mockRepository;
private ICommentService _service;
private ModelStateDictionary _modelState;
public CommentServiceTest()
{
_modelState = new ModelStateDictionary();
_mockRepository = new Mock<IRepository<Comment>>();
_service = new CommentService(new ModelStateWrapper(_modelState), _mockRepository.Object);
}
[Fact]
public void Delete()
{
var comment = new Comment("BodyText")
{
Audio = new Audio(),
Date = DateTime.Now
};
_mockRepository.Object.Add(comment);
//Nothing in repository collection here still
var commentToDelete = _mockRepository.Object.GetAll().First();
_service.Delete(commentToDelete);
Assert.DoesNotContain(commentToDelete, _mockRepository.Object.GetAll());
}
}
public class Repository<T, TC> : IRepository<T> where T : class where …Run Code Online (Sandbox Code Playgroud) moq ×10
c# ×8
unit-testing ×8
mocking ×3
nunit ×2
asp.net-mvc ×1
generics ×1
inheritance ×1
nest ×1
tdd ×1
testing ×1
typemock ×1