We're sorry Aspose doesn't work properply without JavaScript enabled.

Free Support Forum - aspose.com

Unit Tests to Validate Mail Merge Output, Ensure all Mail Merge Fields are Mapped


I wonder if anybody has any suggestions as to how I can create tests that validate the output of MailMerge.Execute().

In particular I want to make sure that all fields in the word template are mapped, and that the mapped values are as expected.

The reason for creating this test is that I need to make sure that changes in the business logic does not break the generated documents, and neither changes to the word templates.

Thanks in advance


I think, you can meet this requirement by using the following simple code:

Document doc = new Document("E:\\Temp\\in.docx");
DocumentBuilder builder = new DocumentBuilder(doc);

// encapsultae mergefields inside temporary bookmarks
foreach (Field field in doc.Range.Fields)
    if (field.Type == Aspose.Words.Fields.FieldType.FieldMergeField)
        FieldMergeField mf = (FieldMergeField)field;
        builder.MoveToMergeField(mf.FieldName, false, false);
        builder.StartBookmark("_" + mf.FieldName);
        BookmarkEnd end = builder.EndBookmark("_" + mf.FieldName);
        mf.End.ParentNode.InsertAfter(end, mf.End);

// lets first check if all merge fields are indeed merged
foreach (string str in doc.MailMerge.GetFieldNames())

doc.MailMerge.Execute(new string[] { "mf1", "mf2" }, new string[] { "field 1 value", "value for field 2" });

foreach (string str in doc.MailMerge.GetFieldNames())

// now lets confirm mergefields are replaced with correct values
foreach (Bookmark bm in doc.Range.Bookmarks)
    if (bm.Name.StartsWith("_"))