简体   繁体   中英

using Moq and NUnit , what is write approach / better syntax?

I am trying to test this behavior

-- BLOGTableAdapter.GetBlogsByTitle(string title) is called and for once only

-- and is called with string having length greater than 1,

-- and it returns BLOGDataTable Object

 [Test]
    public void GetBlogsByBlogTitleTest4()
    {
        var mockAdapter = new Mock<BLOGTableAdapter>();
        var mockTable = new Mock<BLOGDataTable>();

        mockAdapter.Setup(x => x.GetBlogsByTitle(It.Is<string>(s => s.Length > 0))).Returns(mockTable.Object);

        var blogBl = new BlogManagerBLL(mockAdapter.Object);
        blogBl.GetBlogsByBlogTitle("Thanks for reading my question");

        mockAdapter.VerifyAll();
        mockAdapter.Verify(x => x.GetBlogsByTitle(It.Is<string>(s => s.Length > 0)), Times.Exactly(1));
    }

When a calls is made to GetBlogsByTitle(string title), in class say "BlogManagerBLL" in Data Aceess Layer

public BLOGDataTable GetBlogsByBlogTitle(string title)
        {
            return Adapter.GetBlogsByTitle(title);
        }

As you can see, I am using two seperate statements to get these checks done

mockAdapter.Setup(x => x.GetBlogsByTitle(It.Is<string>(s => s.Length > 0))).Returns(mockTable.Object);    
mockAdapter.Verify(x => x.GetBlogsByTitle(It.Is<string>(s => s.Length > 0)), Times.Exactly(1));
  1. How can I put this into one statement ?
  2. Am I testing right things ?

Thanks

If you're testing two things, you should write two tests.

[Test]
public void BlogTableAdapter_should_be_called_with_string_having_length_greater_than_1()
{
    var mockAdapter = new Mock<BLOGTableAdapter>();

    var blogBl = new BlogManagerBLL(mockAdapter.Object);
    blogBl.GetBlogsByBlogTitle("Thanks for reading my question");

    mockAdapter.Verify(x => x.GetBlogsByTitle(It.Is<string>(s => s.Length > 0)));
}

and

[Test]
public void BlogTableAdapter_should_return_a_BLOGDataTable_object()
{
    var mockAdapter = new Mock<BLOGTableAdapter>();
    mockAdapter.Setup(x => x.GetBlogsByTitle(It.Is<string>(s => s.Length > 0))).Returns(new BLOGDataTable());

    var blogBl = new BlogManagerBLL(mockAdapter.Object);
    var returnValue = blogBl.GetBlogsByBlogTitle("Thanks for reading my question");

    Assert.That(returnValue, Is.TypeOf(typeof(BLOGDataTable)));
}

So I guess my advice is don't put them together, create a test for each. And I'd say you're testing the right things.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM