我正在修改一个类方法,该方法格式化一些输入参数日期,这些日期随后在方法调用中用作参数调用到基类(它存在于另一个程序集中).
我想验证传递给我的方法的日期在传递给基类方法时格式正确所以我想要Moq基类方法调用.Moq可以实现吗?
我有一个具有内部方法的类,我想模拟内部方法.但是我无法模仿它,即它不是调用模拟函数而是调用原始函数.有没有办法实现这个目标?
编辑:其实我是Moq的新手.我有许多类的类和方法来使用Moq进行测试.许多类是内部的,许多具有内部方法,许多具有非虚方法.并且无法更改方法和类的签名.任何人都可以让我知道如何使用Moq测试这个场景.或者请建议我一些易于学习和易于使用的其他测试框架.
因此情况是这样的:用户执行某些操作(例如获得徽章或解锁某些内容)并发送电子邮件通知.一个给用户(有一条消息,比如"你已解锁XYZ ......"),然后向他们的每个朋友发送一条不同的消息("你的朋友已解锁XYZ ......").
public interface INotify
{
void Notify(User user, User friend);
}
public class NotificationService
{
private IEnumerable<INotify> _notifiers;
public NotificationService(IEnumerable<INotify> notifiers)
{
_notifiers = notifiers;
}
public SendNotifications()
{
User user = GetUser();
IEnumerable<User> friends = GetFriends();
foreach(var notifier in _notifiers)
{
//Send notification to user
notifier.Notify(user, null);
//send notification to users friends
foreach(var friend in friends)
notifier.Notify(user, friend);
}
}
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试使用moq来测试每个通知符被称为2x.一旦将null作为第二个参数传递,第二次将值传递给两个参数.
[Test]
public void MakeSureEveryoneIsNotified()
{
var notifierMock = new Mock<INotifier>();
var svc = new NotificationService(new …Run Code Online (Sandbox Code Playgroud) 我需要模拟一个接口来调用MSMQ,有没有一种方法我可以使用Moq模拟真实的MSMQ场景,队列中有10条消息,我调用模拟函数10次,我可以获得一个预定义的对象,第11次我应该得到不同的返回值(例如null)?
我的单元测试我的WEB API控制器有问题,我正在使用moq模拟我的存储库,进行设置和响应.然后使用模拟存储库启动控制器.问题是当我尝试从控制器执行调用时,我得到一个异常:
尝试通过方法'System.Web.Http.HttpConfiguration..ctor(System.Web.Http.HttpRouteCollection)'访问方法'System.Web.Http.HttpConfiguration.DefaultFormatters()'失败.
在EyeShield.Api.Tests.PersonsControllerTests.Get_Persons_ReturnsAllPersons()的System.Web.Http.HttpConfiguration..ctor()的System.Web.Http.HttpConfiguration..ctor(HttpRouteCollection路由)中
说实话,不知道这里可能出现什么问题.有谁知道这里可能存在什么问题?
控制器:
using System;
using System.Net;
using System.Net.Http;
using EyeShield.Api.DtoMappers;
using EyeShield.Api.Models;
using EyeShield.Service;
using System.Web.Http;
namespace EyeShield.Api.Controllers
{
public class PersonsController : ApiController
{
private readonly IPersonService _personService;
public PersonsController(IPersonService personService)
{
_personService = personService;
}
public HttpResponseMessage Get()
{
try
{
var persons = PersonMapper.ToDto(_personService.GetPersons());
var response = Request.CreateResponse(HttpStatusCode.OK, persons);
return response;
}
catch (Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, e.Message);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
Global.asax中:
using EyeShield.Data.Infrastructure;
using EyeShield.Data.Repositories;
using EyeShield.Service;
using Ninject;
using …Run Code Online (Sandbox Code Playgroud) 我有以下类,我正在尝试测试方法AddRecordToQueue.
我正在使用Moq来模拟AddRecordToQueue方法中AddToQueue方法的结果.
AddToQueue方法返回一个布尔值,所以我试图用真值模拟结果
public class Test
{
private readonly IRabbitMqConnection rabbitMqConnection;
public Test(IRabbitMqConnection rabbitMqConnection)
{
this.rabbitMqConnection = rabbitMqConnection;
}
public bool AddRecordToQueue(string messageExchange, object data)
{
var jsonified = JsonConvert.SerializeObject(data);
var customerBuffer = Encoding.UTF8.GetBytes(jsonified);
var result = this.rabbitMqConnection.AddToQueue(customerBuffer, messageExchange);
return result;
}
}
Run Code Online (Sandbox Code Playgroud)
我的测试类如下所示.
[TestClass]
public class TestCon
{
[TestMethod]
public void MockTest()
{
Moq.Mock<IRabbitMqConnection> rabbitConection = new Moq.Mock<IRabbitMqConnection>();
var draftContactsManager = new Test(rabbitConection.Object);
rabbitConection.Setup(e => e.AddToQueue(null, string.Empty)).Returns((bool res) => true);
var result = draftContactsManager.AddRecordToQueue("someExchange", null);
Assert.IsTrue(result);
}
}
Run Code Online (Sandbox Code Playgroud)
我似乎无法将moq结果设置为true.任何人都可以建议我缺少什么 …
TypeMock对于像我这样的爱好者来说太贵了:)
Moq或下一版RhinoMocks没有计划收听分析API,为什么会这样?
编辑:这启用以下功能:
It.IsAny<string>()在每次通话时可能导致返回null的原因是什么?假设它被设计为返回非空字符串,我是不正确的?
这是用法 - Login方法为null第二个参数(连接字符串)抛出ArgumentNullException.我假设这It.IsAny<string>()将提供一个非空字符串,它将绕过ArgumentNullException.
var mockApiHelper = new Mock<ApiHelper>();
mockApiHelper.Setup(m => m.Connect(It.IsAny<string>(),
It.IsAny<string>(),
It.IsAny<string>()));
var repositoryPlugin = new RepositoryPlugin(mockApiHelper.Object);
repositoryPlugin.Login(new CredentialsInfo(), It.IsAny<string>());
Assert.IsTrue(repositoryPlugin.LoggedIn,
"LoggedIn property should be true after the user logs in.");
Run Code Online (Sandbox Code Playgroud) 我试图发现如何将async和await关键字应用于我的xUnit测试.我使用的是xUnit 1.9和Async CTP 1.3.这是我的测试用例
我有一个接口,它指定一个异步方法调用
public interface IDoStuffAsync
{
Task AnAsyncMethod(string value);
}
Run Code Online (Sandbox Code Playgroud)
我有一个使用接口并调用异步方法的类
public class UseAnAsyncThing
{
private readonly IDoStuffAsync _doStuffAsync;
public UseAnAsyncThing(IDoStuffAsync doStuffAsync)
{
_doStuffAsync = doStuffAsync;
}
public async Task DoThatAsyncOperation(string theValue)
{
await _doStuffAsync.AnAsyncMethod(theValue);
}
}
Run Code Online (Sandbox Code Playgroud)
在我的测试中,我希望检查方法DoThatAsyncOperation是否使用正确的值调用方法,因此我模拟了接口并使用Moq来验证调用
[Fact]
public async void The_test_will_pass_even_though_it_should_fail()
{
var mock = new Mock<IDoStuffAsync>();
var sut = new UseAnAsyncThing(mock.Object);
mock.Setup(x => x.AnAsyncMethod(It.IsAny<string>()));
await sut.DoThatAsyncOperation("test");
// This won't throw a Moq.MockExcpetion so the test appears to pass
// However it does …Run Code Online (Sandbox Code Playgroud) 我是第一次尝试使用.NET Core,看看Moq如何用于单元测试.开箱即用,创建控制器,其中ApplicationDbContext是构造函数的参数,如下所示:
public class MoviesController : Controller
{
private readonly ApplicationDbContext _context;
public MoviesController(ApplicationDbContext context)
{
_context = context;
}
Run Code Online (Sandbox Code Playgroud)
这是我在测试控制器时开始的单元测试:
[TestClass]
public class MvcMoviesControllerTests
{
[TestMethod]
public async Task MoviesControllerIndex()
{
var mockContext = new Mock<ApplicationDbContext>();
var controller = new MoviesController(mockContext.Object);
// Act
var result = await controller.Index();
// Assert
Assert.IsInstanceOfType(result, typeof(ViewResult));
}
Run Code Online (Sandbox Code Playgroud)
但后来我意识到ApplicationDbContext是一个具体的类,它没有无参数构造函数,所以测试不起作用.它给了我错误:找不到无参数构造函数.
也许这可能是一个更多针对Moq而不是与.NET Core相关的问题,但我也是Moq的新手,所以我不知道如何继续.以下是创建项目时ApplicationDbContext代码的生成方式:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
// Customize the …Run Code Online (Sandbox Code Playgroud) moq ×10
c# ×5
unit-testing ×4
.net ×2
.net-4.0 ×1
asp.net-core ×1
async-await ×1
mocking ×1
rhino-mocks ×1
tdd ×1
testing ×1
xunit.net ×1