对于我的一些单元测试,我必须调用需要Window作为参数的方法。不幸的是我无法传递null,因为该方法使用窗口作为参考来更新状态栏,在那里我显示实际应用程序中实际加载的内容。
所以我试着在单元测试中调用构造函数:
MainWindow window = new MainWindow();
但是这会导致MainWindow构造函数的InitializeComponent方法出现以下错误:
System.Windows.Markup.XamlParseException occurred
Message='Provide value on 'System.Windows.Baml2006.TypeConverterMarkupExtension' threw an exception.' Line number '9' and line position '42'.
Source=PresentationFramework
LineNumber=9
LinePosition=42
StackTrace:
at System.Windows.Markup.XamlReader.RewrapException(Exception e, IXamlLineInfo lineInfo, Uri baseUri)
InnerException: System.IO.IOException
Message=Assembly.GetEntryAssembly() returns null. Set the Application.ResourceAssembly property or use the pack://application:,,,/assemblyname;component/ syntax to specify the assembly to load the resource from.
Source=PresentationFramework
StackTrace:
at MS.Internal.AppModel.ResourceContainer.GetResourceManagerWrapper(Uri uri, String& partName, Boolean& isContentFile)
at MS.Internal.AppModel.ResourceContainer.GetPartCore(Uri uri)
at System.IO.Packaging.Package.GetPartHelper(Uri partUri)
at System.IO.Packaging.Package.GetPart(Uri partUri)
at System.IO.Packaging.PackWebResponse.CachedResponse.GetResponseStream()
at System.IO.Packaging.PackWebResponse.GetResponseStream()
at System.IO.Packaging.PackWebResponse.get_ContentType()
at System.Windows.Media.Imaging.BitmapDecoder.SetupDecoderFromUriOrStream(Uri uri, Stream stream, BitmapCacheOption cacheOption, Guid& clsId, Boolean& isOriginalWritable, Stream& uriStream, UnmanagedMemoryStream& unmanagedMemoryStream, SafeFileHandle& safeFilehandle)
at System.Windows.Media.Imaging.BitmapDecoder.CreateFromUriOrStream(Uri baseUri, Uri uri, Stream stream, BitmapCreateOptions createOptions, BitmapCacheOption cacheOption, RequestCachePolicy uriCachePolicy, Boolean insertInDecoderCache)
at System.Windows.Media.Imaging.BitmapFrame.CreateFromUriOrStream(Uri baseUri, Uri uri, Stream stream, BitmapCreateOptions createOptions, BitmapCacheOption cacheOption, RequestCachePolicy uriCachePolicy)
at System.Windows.Media.ImageSourceConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value)
at System.Windows.Baml2006.TypeConverterMarkupExtension.ProvideValue(IServiceProvider serviceProvider)
at MS.Internal.Xaml.Runtime.ClrObjectRuntime.CallProvideValue(MarkupExtension me, IServiceProvider serviceProvider)
InnerException:
所以我的问题是,如何在单元测试中实例化或模拟窗口?
答案 0 :(得分:18)
尝试以下方法:
if(Application.ResourceAssembly == null)
Application.ResourceAssembly = typeof(MainWindow).Assembly;
var window = new MainWindow();
答案 1 :(得分:3)
简短的回答是你不应该。单元测试未在UI 上完成。
应该在逻辑代码上运行单元测试,这就是MVC和MVVM之类的模式可以提供帮助的地方。应使用CodedUI等工具测试UI。
如果你的逻辑依赖于UI,那么你做错了。