簡體   English   中英

如果單獨運行,則MSTest測試成功;如果與其他測試一起運行,則測試失敗

[英]MSTest tests succeed if run in isolation, fail if run with other tests

我碰到了這種非常奇怪的情況,如果我一起運行所有測試,則某些測試將失敗(其中約7個)。 但是,如果我僅在類內部運行測試(它們都是同一類的一部分),則它們會通過。 測試項目是Windows Phone 8.1 MSTest,我嘗試使用Resharper測試運行程序和MSTest測試運行程序運行它,它們都顯示相同的問題。 這是我的TestInitialize代碼:

[TestInitialize]
public void Init()
{
     ResolveDependencies();
     var adsApiService = ServiceLocator
         .Current
         .GetInstance<IApiService<ListAdsReply, PublicAdsEndPoint>>();            
     var navigationService = new NavigationServiceMock();
     var mainPageTrackingService = ServiceLocator
         .Current
         .GetInstance<IMainPageTrackingService>();
     var adInsertionTrackingService = ServiceLocator
         .Current
         .GetInstance<IAdInsertionTrackingService>();
     var connectionService = ServiceLocator
         .Current
         .GetInstance<IConnectionService>();
     _windowsApiService = new WindowsApiServiceMock();
     var contactAboutTrackingService = ServiceLocator
         .Current
         .GetInstance<IContactAboutTrackingService>();
     var filtersTrackingService = ServiceLocator
         .Current
         .GetInstance<IFiltersTrackingService>();
            var filtersService = ServiceLocator
         .Current
         .GetInstance<IFiltersService>();
     var messageHelperMock = new MessageHelperMock();
     _mainPageViewModel = new MainPageViewModel(adsApiService, navigationService, mainPageTrackingService, adInsertionTrackingService, connectionService, _windowsApiService, contactAboutTrackingService,filtersTrackingService, filtersService, messageHelperMock);
}

除了在Unity容器中注冊依賴項,在ServiceLocator.SetLocatorProvider注冊依賴項並進行一些Automapper配置外, ResolveDependencies方法沒有做任何特殊的事情。 那里沒有異步代碼。

[TestMethod]
public async Task GivenParameterIsProvidedThenFetchDataShouldReturnValidData()
{
    _mainPageViewModel
        .SearchParams
        .Add(new KeyValuePair<string, string>("lim", "5"));
    var searchParams = _mainPageViewModel.SearchParams;
    await _mainPageViewModel.FetchData(searchParams);

    var list = _mainPageViewModel.AdsList;
    Assert.IsNotNull(list);
}

這是失敗的測試之一。

public async Task<ListAdsReplyViewModel> FetchData(List<KeyValuePair<string, string>> parameters)
{
    _cancellationTokenSource = new CancellationTokenSource();

    _cancellationTokenSource
        .CancelAfter(Constants.TimeToCancelAsyncOperations);
    AddSearchKeywordToSearchParams();
    var result = await _listAdsReplyApiService
        .GetWithParametersAsync(_cancellationTokenSource, parameters);
    var vm = new ListAdsReplyViewModel
    {
        Ads = new List<AdInfoViewModel>()
    };
    foreach (var listAd in result.ListAds)
    {
        var listAdDto = Mapper.Map<ListAdDto>(listAd);
        var adInfo = new AdInfoViewModel(_navigationService, _mainPageTrackingService)
        {
            ListAdDto = listAdDto
        };
            vm.Ads.Add(adInfo);
     }
     vm.NextPage = result.NextPage;
     vm.ConfigEtag = result.ConfigEtag;
     vm.Sorting = result.Sorting;
     TotalAds = result.ListAdsCounterMap.AllAds;
     return vm;
}

private void AddSearchKeywordToSearchParams()
{
     if (!string.IsNullOrEmpty(SearchKeyWord))
     {
         var searchKeyword = SearchParams
             .FirstOrDefault(x => x.Key == "q");
         if (!searchKeyword.Equals(null))  
             SearchParams.Remove(searchKeyword);
         SearchParams.Add(new KeyValuePair<string, string>("q", SearchKeyWord));
     }
}

這是正在測試的方法。 當調用foreach((var listAd in result.ListAds)時,似乎發生了問題。就像沒有等待GetWithParametersAsync(_cancellationTokenSource, parameters); ,因為失敗的測試會出現以下錯誤:

Test method App.Tests.Integration.App.Shared.ViewModels.MainPageViewModelTests.GivenParameterIsProvidedThenFetchDataShouldReturnValidData threw exception: 
AutoMapper.AutoMapperMappingException: 

Mapping types:
ListAd -> ListAdDto
Core.Api.Models.PublicAds.ListAd -> Core.Dto.ListAdDto

Destination path:
ListAdDto

Source value:
Core.Api.Models.PublicAds.ListAd ---> System.NullReferenceException: Object reference not set to an instance of an object.

    at Core.Bootstrap.AutoMapperConfiguration.<>c__DisplayClass0_0.<Configure>b__12(ListAd src, ListAdDto dest)
   at AutoMapper.Internal.MappingExpression`2.<>c__DisplayClass57_0.<AfterMap>b__0(Object src, Object dest)
   at AutoMapper.TypeMap.<get_AfterMap>b__40_0(Object src, Object dest)
   at AutoMapper.Mappers.TypeMapObjectMapperRegistry.PropertyMapMappingStrategy.Map(ResolutionContext context, IMappingEngineRunner mapper)
   at AutoMapper.Mappers.TypeMapMapper.Map(ResolutionContext context, IMappingEngineRunner mapper)
   at AutoMapper.MappingEngine.AutoMapper.IMappingEngineRunner.Map(ResolutionContext context)
 --- End of inner exception stack trace ---
    at App.ViewModels.MainPageViewModel.<FetchData>d__34.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at App.Tests.Integration.App.Shared.ViewModels.MainPageViewModelTests.<GivenParameterIsProvidedThenFetchDataShouldReturnValidData>d__7.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

有什么想法嗎?

正如評論中所接受的那樣,我已重新發布為答案;

“您是否考慮過MSTest將運行多線程測試,並且通過執行一個測試就強制了一個單線程?請特別注意,所有測試都是UNIT測試,彼此之間沒有依賴性。執行的順序,或者共享資源可能已經被並行運行的另一個測試實例化(或處於實例化過程中)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM