2017-07-17 93 views
0

我嘗試在.net核心中測試控制器,但是在測試中出現錯誤,我無法更正。模擬環境通過將其傳送給控制器而產生問題。上下文的錯誤時間XUnit測試在.net核心的控制器

實施例:

public class TagControllerTest 
{ 
    [Fact] 
    public void SimpleTest() 
    { 
     Assert.Equal(5, 5); 
    } 

    [Fact] 
    public void SimpleTest2() 
    { 
     Assert.Equal(5, 5); 
    } 

    [Fact] 
    public void ControllerGetTest() 
    { 
     //Arrange 
     var data = new List<Tag> 
     { 
      public virtual DbSet<Exercise> ExerciseSet { get; set; } 
      public virtual DbSet<Tag> TagSet { get; set; } 
      public virtual DbSet<Type> TypeSet { get; set; } 
      public virtual DbSet<Difficulty> DifficultySet { get; set; } 
      public virtual DbSet<ExerciseTag> ExerciseTagSet { get; set; } 
      public virtual DbSet<Mark> MarkSet { get; set; } 
      public virtual DbSet<ExerciseMark> ExerciseMarkSet { get; set; } 
     }.AsQueryable(); 

     Mock<DbSet<Tag>> dbSetMock = new Mock<DbSet<Tag>>(); 
     dbSetMock.As<IQueryable<Tag>>().Setup(m => m.Provider).Returns(data.Provider); 
     dbSetMock.As<IQueryable<Tag>>().Setup(m => m.Expression).Returns(data.Expression); 
     dbSetMock.As<IQueryable<Tag>>().Setup(m => m.ElementType).Returns(data.ElementType); 
     dbSetMock.As<IQueryable<Tag>>().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator()); 

     Mock<Context> context = new Mock<Context>(dbSetMock.Object); 
     context.Setup(x => x.TagSet).Returns(dbSetMock.Object); 

     TagController controller = new TagController(context.Object); 

     // Act 
     var result = controller.GetTag(); 

     // Assert 
     Assert.NotNull(result); 
    } 
} 

前兩個測試通過,但第三測試給出了線的錯誤信息::

TagController controller = new TagController(context.Object); 
測試

public class Context : DbContext 
{ 
    public virtual DbSet<Exercise> ExerciseSet { get; set; } 
    public virtual DbSet<Tag> TagSet { get; set; } 
    public virtual DbSet<Type> TypeSet { get; set; } 
    public virtual DbSet<Difficulty> DifficultySet { get; set; } 
    public virtual DbSet<ExerciseTag> ExerciseTagSet { get; set; } 
    public virtual DbSet<Mark> MarkSet { get; set; } 
    public virtual DbSet<ExerciseMark> ExerciseMarkSet { get; set; } 

    public Context(DbContextOptions<Context> options) 
     : base(options) 
    { 
    } 
} 

實施例

消息:Castle.DynamicProxy.InvalidProxyConstructorArguments異常 :無法實例化類的代理:interview.Models.Context。難道 找不到可以匹配給定參數的構造函數: Castle.Proxies.DbSet`1Proxy

回答

0
Mock<Context> context = new Mock<Context>(dbSetMock.Object); 

上下文的構造函數接受DbContextOptions<Context>但你通過DbSet<Tag>

一般情況下,添加一個參數的構造函數或通過類似:

var builder = new DbContextOptionsBuilder<Context>(); 
var options = builder.Options; 
相關問題