2016-02-29 2 views
0

У меня есть проблема, когда я вызвать любую функцию в моем единичном классе тест контроллера, когда я запустить тест, его дают ошибкиссылка на объект не указывает на экземпляр, когда вызов функций в единичном испытании (intellitest)

ссылка на объект не указывает на экземпляр объекта

я не уверен, что я здесь отсутствует или я не знаю, я делаю функцию модульного тестирования вызов, я использую intellitest с помощью Visual Studio 2015 издание для предприятий

вот мой код

  1. /// Этот класс содержит параметризованные модульных тестов для AccountFinFilesController

    [TestClass] 
    [PexClass(typeof(AccountFinFilesController))] 
    [PexAllowedExceptionFromTypeUnderTest(typeof(ArgumentException), AcceptExceptionSubtypes = true)] 
    [PexAllowedExceptionFromTypeUnderTest(typeof(InvalidOperationException))] 
    public partial class AccountFinFilesControllerTest 
    { 
    
        /// <summary>Test stub for .ctor(ISmallBizRepository)</summary> 
        [PexMethod] 
        public AccountFinFilesController ConstructorTest(ISmallBizRepository repo) 
        { 
         AccountFinFilesController target = new AccountFinFilesController(repo); 
         return target; 
         // TODO: add assertions to method AccountFinFilesControllerTest.ConstructorTest(ISmallBizRepository) 
        } 
    
        /// <summary>Test stub for Delete(Guid, Guid)</summary> 
        [PexMethod] 
        public HttpResponseMessage DeleteTest(
         [PexAssumeUnderTest]AccountFinFilesController target, 
         Guid id, 
         Guid deletedby 
        ) 
        { 
         HttpResponseMessage result = target.Delete(id, deletedby); 
         return result; 
         // TODO: add assertions to method AccountFinFilesControllerTest.DeleteTest(AccountFinFilesController, Guid, Guid) 
        } 
    
        /// <summary>Test stub for GetAccountFinFilesTable(Guid, Guid)</summary> 
        [PexMethod] 
        public IQueryable GetAccountFinFilesTableTest(
         [PexAssumeUnderTest]AccountFinFilesController target, 
         Guid firmid, 
         Guid id 
        ) 
        { 
         IQueryable result = target.GetAccountFinFilesTable(firmid, id); 
         Assert.IsNotNull(result); 
         return result; 
         // TODO: add assertions to method AccountFinFilesControllerTest.GetAccountFinFilesTableTest(AccountFinFilesController, Guid, Guid) 
        } 
    
        /// <summary>Test stub for GetAccountFinFilesTable(Guid)</summary> 
        [PexMethod] 
        public IQueryable GetAccountFinFilesTableTest01([PexAssumeUnderTest]AccountFinFilesController target, Guid firmid) 
        { 
    
         IQueryable result = target.GetAccountFinFilesTable(Guid.Parse("75165ae3-cbae-e511-b0bf-00259076695a")); 
         Assert.IsNotNull(result); 
         return result; 
         // TODO: add assertions to method AccountFinFilesControllerTest.GetAccountFinFilesTableTest01(AccountFinFilesController, Guid) 
        } 
    
        /// <summary>Test stub for Post(AccountFinFilesTable, Guid, Guid)</summary> 
        [PexMethod] 
        public HttpResponseMessage PostTest(
         [PexAssumeUnderTest]AccountFinFilesController target, 
         AccountFinFilesTable obj, 
         Guid firmid, 
         Guid createdby 
        ) 
        { 
         HttpResponseMessage result = target.Post(obj, firmid, createdby); 
         return result; 
         // TODO: add assertions to method AccountFinFilesControllerTest.PostTest(AccountFinFilesController, AccountFinFilesTable, Guid, Guid) 
        } 
    
        /// <summary>Test stub for Put(AccountFinFilesTable)</summary> 
        [PexMethod] 
        public HttpResponseMessage PutTest([PexAssumeUnderTest]AccountFinFilesController target, AccountFinFilesTable obj) 
        { 
         HttpResponseMessage result = target.Put(obj); 
         return result; 
         // TODO: add assertions to method AccountFinFilesControllerTest.PutTest(AccountFinFilesController, AccountFinFilesTable) 
        } 
    } 
    
  2. WebAPI класс контроллера

    public class AccountFinFilesController : BaseApiController 
        { 
        private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); 
        public AccountFinFilesController(ISmallBizRepository repo) 
         : base(repo) 
        { 
        } 
    
        // GET api/AccountFinFiles 
        /// <summary> 
        /// GetAccountFinFilesTable 
        /// </summary> 
        /// <param name="firmid"></param> 
        /// <param name="id"></param> 
        /// <returns></returns> 
        [HttpGet] 
        public IQueryable GetAccountFinFilesTable(Guid firmid, Guid id) 
        { 
         log.Info("GetAccountFinFilesTable API -- firmid=" + firmid + "&id=" + id); 
         return TheRepository.GetAccountFinFile(firmid, id); 
        } 
    
        /// <summary> 
        /// GetAccountFinFilesTable 
        /// </summary> 
        /// <param name="firmid"></param> 
        /// <returns></returns> 
        [HttpGet] 
        public IQueryable GetAccountFinFilesTable(Guid firmid) 
        { 
          log.Info("GetAccountFinFilesTable API -- firmid=" + firmid); 
          return TheRepository.GetAccountFinFile(firmid); 
        } 
    
        /// <summary> 
        /// update AccountFinFilesTable 
        /// </summary> 
        /// <param name="account_finfilestabledm"></param> 
        /// <returns></returns> 
        [HttpPut] 
        public HttpResponseMessage Put(AccountFinFilesTable obj) 
        { 
         try 
         { 
          var updatedEntity = TheModelFactory.Parse(obj); 
    
          if (updatedEntity == null) 
          { 
           log.Error(MessagesHelper.recordnotfound + "File_ID: " + obj.File_ID); 
           Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Could not read AccountFinFilesTable from body"); 
          } 
    
          var originalEntity = TheRepository.GetAccountFinFileByPrimaryKey(obj.File_ID); 
    
          if (originalEntity == null || originalEntity.File_ID != obj.File_ID) 
          { 
           log.Error(MessagesHelper.recordnotfound + "File_ID: " + obj.File_ID); 
           return Request.CreateResponse(HttpStatusCode.NotModified, "AccountFinFilesTable record not found"); 
          } 
          else 
          { 
           updatedEntity.File_ID = obj.File_ID; 
          } 
    
          if (TheRepository.Update(originalEntity, updatedEntity) && TheRepository.SaveAll()) 
          { 
           log.Info(MessagesHelper.updatesuccess + "File_ID: " + obj.File_ID); 
           return Request.CreateResponse(HttpStatusCode.OK, TheModelFactory.Create(updatedEntity)); 
          } 
          else 
          { 
           log.Error(MessagesHelper.updateerror + "File_ID: " + obj.File_ID); 
           return Request.CreateResponse(HttpStatusCode.NotModified, "Could not update to the database."); 
          } 
    
         } 
         catch (Exception ex) 
         { 
          log.Error(ex.Message + " " + obj.File_ID); 
          return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); 
         } 
    
        } 
    
        /// <summary> 
        /// add new record to AccountFinFilesTable 
        /// </summary> 
        /// <param name="account_finfilestabledm"></param> 
        /// <param name="firmid"></param> 
        /// <param name="createdby"></param> 
        /// <returns></returns> 
        [HttpPost] 
        public HttpResponseMessage Post(AccountFinFilesTable obj, Guid firmid, Guid createdby) 
        { 
         try 
         { 
          obj.FirmId = firmid; 
          obj.ClientId = createdby; 
          obj.CreatedDate = DateTime.UtcNow; 
    
          var entity = TheModelFactory.Parse(obj); 
    
          if (entity == null) 
          { 
           log.Error(MessagesHelper.recordnotfound + " " + firmid + " " + createdby); 
           return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Could not read AccountFinFilesTable from body"); 
          } 
          else 
          { 
           if (TheRepository.Insert(entity) && TheRepository.SaveAll()) 
           { 
            log.Info(MessagesHelper.savesuccess + " " + firmid + " " + createdby); 
            return Request.CreateResponse(HttpStatusCode.Created, TheModelFactory.Create(entity)); 
           } 
           else 
           { 
            log.Error(MessagesHelper.saverror + " " + firmid + " " + createdby); 
            return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Could not save to the database."); 
           } 
          } 
    
         } 
         catch (Exception ex) 
         { 
          log.Error(ex.Message + " " + firmid + " " + createdby); 
          return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); 
         } 
        } 
    
        /// <summary> 
        /// delete record from AccountFinFilesTable 
        /// </summary> 
        /// <param name="account_finfilestabledm"></param> 
        /// <param name="deletedby"></param> 
        /// <returns></returns> 
        [HttpDelete] 
        public HttpResponseMessage Delete(Guid id, Guid deletedby) 
        { 
         try 
         { 
          var entity = TheRepository.GetAccountFinFileByPrimaryKey(id); 
    
          if (entity == null) 
          { 
           log.Error(MessagesHelper.recordnotfound + "File_ID: " + id); 
           return Request.CreateResponse(HttpStatusCode.NotFound); 
          } 
    
          if (TheRepository.DeleteAccountFinFile(id, deletedby) && TheRepository.SaveAll()) 
          { 
           log.Info(MessagesHelper.deletesuccess + "File_ID: " + entity.File_ID); 
           return Request.CreateResponse(HttpStatusCode.OK); 
          } 
          else 
          { 
           log.Error(MessagesHelper.deleteerror + "File_ID: " + entity.File_ID); 
           return Request.CreateResponse(HttpStatusCode.BadRequest, "Could not delete the record."); 
          } 
    
         } 
         catch (Exception ex) 
         { 
          log.Error(ex.Message + "File_ID: " + id); 
          return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message); 
         } 
    
        } 
    
    } 
    
  3. ошибка

object reference not set to an instance of an object

, пожалуйста, помогите/посоветуйте или предоставите мне полное решение в соответствии с моим сценарием, при необходимости я предоставит более подробную информацию. спасибо за ваше драгоценное время и усилия.

ответ

0

Добавить функцию TestInitialize с этим атрибутом и инициализировать там переменные класса. Затем в точке вы можете использовать свою инициализированную переменную-член во время тестов.

Добавьте функцию CleanUp. См. TestInitializeAttribute

+0

спасибо за ваш ответ, пожалуйста, объясните мне подробно, как использовать в коде, укажите мне пример кода. – adnan

Смежные вопросы