2016-10-07 26 views
1

我正在使用MVVMCross構建一個Xamarin.Forms項目。爲了測試我使用的平臺特定代碼Nunit.Xamarin,它具有一個在設備上運行測試的應用程序。使用MVVMCross SQLite Plugin構建的單元測試代碼

這個測試程序是一個形式的應用程序,但不使用MVVMCross,我已經沒有任何運氣將它設置爲使用MVVMCross由於應用程序類加載類型的應用程序NUnit.Runner.App事實而MVVMCross需要MvxFormsApp

我想測試這個類從SQLite數據庫的保存和讀取用戶數據:

public class DataStorageService : IDataStorageService 
{ 
    private readonly SQLiteConnection _connection; 

    public User UserData 
    { 
     get { return _connection.Table<User>().FirstOrDefault(); } 
     set { _connection.InsertOrReplace(value); } 
    } 

    public DataStorageService(IMvxSqliteConnectionFactory factory) 
    { 
     _connection = factory.GetConnection(DataStorageConstants.LocalDatabaseName); 
     _connection.CreateTable<User>(); 
    } 
    } 

我想實際測試,它保存和從本地SQLite數據庫負載,所以我不希望嘲笑IMvxSqliteConnectionFactory。我嘗試將MVVMCross和SQLite插件安裝到項目中,然後傳遞連接工廠的Android實現,但反覆拋出了typeloadexception。

任何有關如何使用MVVMCross(或有替代方法?)和依賴注入來設置此測試的想法?

回答

3

有可能:)重要的事情發生在MvxSplashScreenActivityMvxFormsApp基本上是空的。所以我們不必關心。示例代碼:https://github.com/smstuebe/stackoverflow-answers/tree/master/mvx-android-test-app

  1. 創建NUnit測試應用項目
  2. Install-Package MvvmCross.StarterPack -Version 4.1.4
  3. 擺脫Views文件夾
  4. 的安裝SQLite的插件
  5. 參考你的核心項目
  6. Install-Package MvvmCross.Forms.Presenter -Version 4.1.4
  7. 刪除MainLauncher = true from MainActivity
  8. Adust Setup返回自己的核心項目App
protected override IMvxApplication CreateApp() 
{ 
    return new MyApp.Core.App(); 
} 
  • 更改閃屏到(source
  • [Activity(MainLauncher = true 
    , Theme = "@style/Theme.Splash" 
    , NoHistory = true 
    , ScreenOrientation = ScreenOrientation.Portrait)] 
    public class SplashScreen 
    : MvxSplashScreenActivity 
    { 
        public SplashScreen() 
         : base(Resource.Layout.SplashScreen) 
        { 
        } 
    
        private bool _isInitializationComplete; 
        public override void InitializationComplete() 
        { 
         if (!_isInitializationComplete) 
         { 
          _isInitializationComplete = true; 
          StartActivity(typeof(MainActivity)); 
         } 
        } 
    
        protected override void OnCreate(Android.OS.Bundle bundle) 
        { 
         Forms.Init(this, bundle); 
         Forms.ViewInitialized += (object sender, ViewInitializedEventArgs e) => 
         { 
          if (!string.IsNullOrWhiteSpace(e.View.StyleId)) 
          { 
           e.NativeView.ContentDescription = e.View.StyleId; 
          } 
         }; 
    
         base.OnCreate(bundle); 
        } 
    } 
    
  • 撰寫測試like
  • [TestFixture] 
    public class TestClass 
    { 
        [Test] 
        public void TestMethod() 
        { 
         var service = Mvx.Resolve<IDataStorageService>(); 
         Assert.IsNull(service.UserData); 
        } 
    } 
    
  • 享受MvvmCross
  • 迷死
    +0

    完美,非常感謝! –