[英]How to unit test that a Windows Workflow Foundation (WF) activity can be serialized?
Problem: during execution, instances of classes that derives from System.Workflow.ComponentModel.Activity
is serialized by the workflow engine. 问题:在执行过程中,从System.Workflow.ComponentModel.Activity
派生的类的实例由工作流引擎序列化。 I'd like to unit test these types in order to ensure that they can be serialized. 我想对这些类型进行单元测试,以确保可以序列化它们。 As of now, these exceptions only show up in production. 到目前为止,这些例外仅在生产中出现。
Non-working solution: 非工作解决方案:
public class UnitTestActivity : Activity
{}
[Test]
public void ShouldBeSerializable()
{
var activity = new UnitTestActivity();
activity.Clone(); // throws exception here
}
The test above yields the following exception "System.InvalidOperationException : This is an invalid design time operation. You can only perform the operation at runtime." 上面的测试产生以下异常“ System.InvalidOperationException:这是无效的设计时操作。您只能在运行时执行该操作。”
I've also tried the activity.Save(...)
method which then throws the same exception. 我也尝试过activity.Save(...)
方法,然后抛出相同的异常。 The code I used is: 我使用的代码是:
public static void SerializeToFile( Activity activity )
{
using (var fileStream = new FileStream( GetFilePath(), FileMode.Create ))
{
IFormatter formatter = new BinaryFormatter { SurrogateSelector = ActivitySurrogateSelector.Default };
activity.Save( fileStream, formatter );
}
}
I think you would need to spin up an instance with a persistence service in the host, and try and persist it. 我认为您将需要在主机中使用持久性服务启动一个实例,然后尝试将其持久化。
(The custom workflow type is itself not serialised when persisting the workflow, but just its state.) (自定义工作流程类型在持久化工作流程时本身不会被序列化,而只是其状态。)
I implemented a workaround solution that loops through all the fields of every Activity
heir and tries to serialize it. 我实现了一种变通方法,该方法遍历每个Activity
继承者的所有字段并尝试对其进行序列化。 The NUnit test looks like so (helpers omitted): NUnit测试看起来像这样(省略了助手):
[Test, TestCaseSource( "GetActivities" )]
public void ShouldBeSerializable( Activity activity )
{
var fieldInfos = activity.GetType().GetFields( BindingFlags.Public | BindingFlags.NonPublic
| BindingFlags.Instance | BindingFlags.Static );
fieldInfos.Where( fieldInfo => fieldInfo.Name != "parent" )
.ForEach( fieldInfo =>
{
var fieldValue = fieldInfo.GetValue( activity );
if ( fieldValue != null )
{
Serializer.Clone( fieldValue ); // no assert, throws exception if not serializable
}
} );
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.