Skip to main content

UL and LI list elements in WatiN

Update 2011-02-16: This is no longer needed as of Watin 2.0 Final Release.

I've been missing the UL/LI element querying in WatiN since I started to use it, but I've never even thought about doing something about it. Thanks to WatiN's excellent extensibility it was proven not too hard.

[ElementTag("ul")]
public class Ul : ElementContainer<Ul>
{
 public Ul(DomContainer domContainer, INativeElement nativeElement) : base(domContainer, nativeElement)
 {
 }

public Ul(DomContainer domContainer, ElementFinder elementFinder) : base(domContainer, elementFinder) { }

public LiCollection Items { get { return new LiCollection(DomContainer, CreateElementFinder<Li>( delegate(INativeElement nativeElement) { return nativeElement.Children; }, null)); } } }

[ElementTag("li")] public class Li : ElementContainer<Li> { public Li(DomContainer domContainer, INativeElement nativeElement) : base(domContainer, nativeElement) { }

public Li(DomContainer domContainer, ElementFinder finder) : base(domContainer, finder) { } }

public class LiCollection : BaseElementCollection<Li, LiCollection> { public LiCollection(DomContainer domContainer, ElementFinder elementFinder) : base(domContainer, elementFinder) { }

protected override LiCollection CreateFilteredCollection(ElementFinder elementFinder)
{
    return new LiCollection(DomContainer, elementFinder);
}

}

You'll notice at once that most of the code is inheritence and calling base. The magic is all in the type declarations and their ElementTag-attributes. Now you can use the UL element in a page declaration to give easy access to the UL list.

404: Not Found

public class IndexView : Page
{
    private const string ColorListId = "colors";

public Ul ColorList
{
    get { return Document.ElementOfType&lt;Ul&gt;(ColorListId); }
}

}

And you use this in a test as usual.

[Test]
public void ShouldHaveListWithThreeColors()
{
    using (var browser = new IE("http://localhost:51562"))
    {
        var index = browser.Page<IndexView>();

    Assert.That(index.ColorList.Items.Count, Is.EqualTo(3));
    Assert.That(index.ColorList.Items[0].Text.Trim(), Is.EqualTo(&quot;Blue&quot;));
    Assert.That(index.ColorList.Items[1].Text.Trim(), Is.EqualTo(&quot;Green&quot;));
    Assert.That(index.ColorList.Items[2].Text.Trim(), Is.EqualTo(&quot;White&quot;));
}

}

This was made with WatiN 2.0 RC 1. You can download the complete source and example here.

comments powered by Disqus