我有一个XrmServiceContext类,每次CRM配置更改时它都会更改。
我的服务类在其构造函数中接受它:
public class fooService(XrmServiceContext xrmServiceContext)
{
//implementation
}
Run Code Online (Sandbox Code Playgroud)
我需要模拟XrmServiceContext以便设置期望并验证单元测试的行为。
我如何模拟此类以便在我的fooService测试中定义行为?
我正在尝试创建一个测试以测试实体框架Add方法。任何人都可以帮助模拟该DbSet.Add方法。我已经尝试了如下但不能正常工作。我究竟做错了什么?
我得到的结果是null在repository.Insert... 之后
Test.cs:
var productToCreate = new Product { Name = "Added", Description = "Added" };
var result = repository.InsertAsync(objToCreate, userContext).Result;
Assert.AreEqual(result.Name, "Added");
Run Code Online (Sandbox Code Playgroud)
Mock.cs
internal static DbSet<T> GetMockedDataSet<T>(IEnumerable<T> data) where T : class
{
// Create a mocked data set that contains the data
var set = new Mock<DbSet<T>>();
set.As<IDbAsyncEnumerable<T>>()
.Setup(m => m.GetAsyncEnumerator())
.Returns(new TestDbAsyncEnumerator<T>(data.GetEnumerator()));
set.As<IQueryable<T>>()
.Setup(m => m.Provider)
.Returns(new TestDbAsyncQueryProvider<T>(data.AsQueryable().Provider));
set.As<IQueryable<T>>().Setup(m => m.Expression).Returns(data.AsQueryable().Expression);
set.As<IQueryable<T>>().Setup(m => m.ElementType).Returns(data.AsQueryable().ElementType);
set.As<IQueryable<T>>().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator());
set.Setup(x …Run Code Online (Sandbox Code Playgroud) 我有一个DbSet,我已经嘲笑和暴露.我把一些部门填满了上下文.当我访问这些部门时,我得到null.
private Mock<DbSet<Department>> departmentSet;
private Mock<DemoEntities> context;
[TestInitializeAttribute()]
public void TestInit()
{
context = new Mock<DemoEntities>();
departmentSet = new Mock<DbSet<Department>>();
context.Setup(c => c.Departments).Returns(departmentSet.Object);
context.Object.Departments.Add(new Department() { Name = "HR", Id = 1 });
context.Object.Departments.Add(new Department() { Name = "Operations", Id = 2 });
context.Object.SaveChanges();
var list = context.Object.Departments; //returns null
}
Run Code Online (Sandbox Code Playgroud)
任何人都可以让我知道我做错了什么.其他测试用例依赖于访问context.Object.Departments.
好的,有人问我:
鉴于这门课程
public class ModelWrapper
{
private Customer _customer; // Entity Framework POCO model
public ModelWrapper(Customer model)
{
if (model == null)
throw new ArgumentNullException("model");
_customer = model;
}
}
Run Code Online (Sandbox Code Playgroud)
使用Moq编写单元测试来测试传入null参数时抛出ArugmentNullException.注意:您不需要实现接口
好的,所以我认为可以在xUnit中使用这样的东西:
[Fact]
public void ShouldTestArgumentNullException()
{
var test = Assert.Throws<ArgumentNullException>(
new ModelWrapper(null)
);
Assert.Equal(test.ParamName,"model");
}
Run Code Online (Sandbox Code Playgroud)
即使这有效,但这不是正确的答案.然后我尝试了这个:
_mock.Setup( w => new ModelWrapper(null)).Throws(new ArgumentNullException("model"));
_mock.Verify();
Run Code Online (Sandbox Code Playgroud)
这不行,我得到了这个例外:
消息:System.ArgumentException:Expression不是方法调用:w => new ModelWrapper(null)
那么,正确的答案是什么?
编辑更新:有人告诉我,我只能在Moq使用一个具体的类,如下所示:
var _mock = new Mock<ModelWrapper>();
Run Code Online (Sandbox Code Playgroud)
但是,我仍然没有看到如何做到这一点.正如您在使用具体类ModelWrapper编写代码时所看到的那样,它仍然失败了.
我正在使用Moq和Nunit Framework对我的Controller中的一个方法进行单元测试.我正在努力理解Mocking存储库和其他对象的概念,但没有取得多大成功.
我有一种方法,不允许用户删除在他/她的帐户中有未结余额的学生.该方法的逻辑在我的StudentController中,在POST方法中,我也使用存储库和依赖注入(不确定是否导致问题).当我运行我的单元测试时,有时它会转到我的GET Delete()方法,如果它进入POST method我得到一个错误,说"对象引用未设置为对象的实例"代码行说这个if (s.PaymentDue > 0)?
StudentController
public class StudentController : Controller
{
private IStudentRepository studentRepository;
public StudentController()
{
this.studentRepository = new StudentRepository(new SchoolContext());
}
public StudentController(IStudentRepository studentRepository)
{
this.studentRepository = studentRepository;
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Delete(int id)
{
//studentRepository.DeleteStudent(id);
Student s = studentRepository.GetStudentByID(id);
var paymentDue = false;
if (s.PaymentDue > 0)
{
paymentDue = true;
ViewBag.ErrorMessage = "Cannot delete student. Student has overdue payment. Need to CLEAR payment before deletion!"; …Run Code Online (Sandbox Code Playgroud) 我正在使用C#MOQ库.
让我们说我想UnitTest为这段代码创建一个:
if(condition){
privateMethod();
}
else{
logger.info("didn't hit")
}
Run Code Online (Sandbox Code Playgroud)
我想检查是否privateMethod被击中,我不能使用该Verify功能,因为它是私人的.我怎样才能做到这一点?
我想添加一个Status专门用于单元测试的成员,它将在退出测试方法之前保留最后一个位置.
我有一个控制器:
public class SelectController : Controller {
private readonly IChartService _chartService;
private readonly IProductService _productService;
private readonly IStoreService _storeService;
public SelectController ( IChartService chartService,
IProductService productService,
IStoreService storeService ) {
_chartService = chartService;
_productService = productService;
_storeService = storeService;
}
[HttpGet]
[Route( "stores" )]
public Task<IEnumerable<IStore>> GetStoresInfo ( string encryptedUserId ) {
return _storeService.GetStoresInfo( EncryptionProvider.Decrypt( encryptedUserId ) );
}
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试GetStoresInfo使用Moq 进行测试.这就是我到目前为止所做的一切:
[Fact]
public class Controller_Returns_List_Of_Stores()
{
//Arrange
var mockStoreService = new Mock<IStoreService>();
var mockChartService = new Mock<IChartService>(); …Run Code Online (Sandbox Code Playgroud) 我有一个Entity Framework数据库上下文文件.我正在尝试在NUnit中设置Moq框架.目前收到Moq Nunit测试的错误.如何设置DBContext,并将项目添加到产品表?
"没有为此DbContext配置数据库提供程序.可以通过覆盖DbContext.OnConfiguring方法或在应用程序服务提供程序上使用AddDbContext来配置提供程序.如果使用AddDbContext,则还要确保您的DbContext类型接受DbContextOptions对象它的构造函数并将其传递给DbContext的基础构造函数."
Electronics DB上下文文件
public partial class ElectronicsContext : DbContext
{
public ElectronicsContext()
{
}
public ElectronicsContext(DbContextOptions<ElectronicsContext> options)
: base(options)
{
}
public virtual DbSet<Product> Product { get; set; }
public virtual DbSet<ProductCategory> ProductCategory { get; set; }
Run Code Online (Sandbox Code Playgroud)
Startup.cs
var connection = @"Server=localhost;Database=Electronics;Trusted_Connection=True;ConnectRetryCount=0";
services.AddDbContext<ElectronicsContext>(options => options.UseSqlServer(connection));
Run Code Online (Sandbox Code Playgroud)
Moq Nunit测试
[SetUp]
public void Setup()
{
var ElectronicsContext = new Mock<ElectronicsContext>();
var ProductRepository = new Mock<ProductRepository>();
Product producttest = new Product();
_dbContext.Product.Add(new Product {ProductId = 1, ProductName = "TV", ProductDescription = …Run Code Online (Sandbox Code Playgroud) 我是nUnit和Moq进行单元测试的新手,并且在dbprovider中遇到了一个方法的问题.
我正在尝试测试在ICoDbProvider中调用Exists方法的验证方法.如果为false,则该方法会抛出一个excpetion,并且工作正常.如果为true,则该方法应该继续执行,直到return true;方法结束时的语句为止.
这是测试的方法:
private bool ValidateReciboCajaModel(ReciboCajaModel model)
{
if (model == null)
throw new ArgumentException("El modelo ha llegado nulo");
if (string.IsNullOrWhiteSpace(model.AccionARealizar))
throw new ArgumentException("No se ha definido una Acción a realizar");
if (!_accionARealizarService.Exists(new AccionARealizarEntity(model)))
throw new ArgumentException(@"No es una ""acción a realizar"" válida");
if (string.IsNullOrWhiteSpace(model.CentroCostos))
throw new ArgumentException("No se ha definido ningún centro de costos");
if (!_centroCostosService.Exists(new CentroCostosEntity(model)))
throw new Exception("No es un centro de costos válido");
if (String.IsNullOrWhiteSpace(model.CuentaIngresoDinero))
throw new Exception("No es una cuenta de Ingreso …Run Code Online (Sandbox Code Playgroud) 我正在尝试测试使用两个不同接口的方法。使用Moq,我可以配置interfaces方法并设置一个return对象,但是无论我设置为Returns,只是执行的第一个方法都返回值,第二个方法返回null。
这是一个例子:
接口1
public interface IUserRepository
{
User GetUserById(int id);
}
Run Code Online (Sandbox Code Playgroud)
接口2
public interface ICallApiService
{
ApiResponseDto ValidateUser();
}
Run Code Online (Sandbox Code Playgroud)
我要测试的课程
public class UserServices : IUserServices
{
private IUserRepository _userRepository;
private ICallApiService _callApiService;
public UserServices(IUserRepository userRepository, ICallApiService callApiService)
{
_userRepository = userRepository;
_callApiService = callApiService;
}
public User GetUserById(int id)
{
//result always have a value set to result
var result = _callApiService.ValidateUser();
//result2 is always null
var result2 = _userRepository.GetUserById(result.UserId);
return result2;
}
}
Run Code Online (Sandbox Code Playgroud)
测试方法
[TestMethod]
public void TestMethod1()
{ …Run Code Online (Sandbox Code Playgroud) c# ×10
moq ×10
unit-testing ×7
nunit ×3
asp.net-mvc ×2
.net ×1
.net-core ×1
asp.net ×1
asp.net-core ×1
c#-4.0 ×1
interface ×1