使用NUnit测试项目列表

时间:2010-12-19 18:55:48

标签: unit-testing nunit moq

告诉我,我的概念是否错误。我有2节课; CountryState。州将拥有CountryId财产。

我有一个服务和存储库,如下所示:

Service.cs

    public LazyList<State> GetStatesInCountry(int countryId)
    {
        return new LazyList<State>(geographicsRepository.GetStates().Where(s => s.CountryId == countryId));
    }

IRepository.cs

public interface IGeographicRepository
{
    IQueryable<Country> GetCountries();

    Country SaveCountry(Country country);

    IQueryable<State> GetStates();

    State SaveState(State state);
}

MyTest.cs

    private IQueryable<State> getStates()
    {
        List<State> states = new List<State>();
        states.Add(new State(1, 1, "Manchester"));//params are: StateId, CountryId and StateName
        states.Add(new State(2, 1, "St. Elizabeth"));
        states.Add(new State(2, 2, "St. Lucy"));
        return states.AsQueryable();
    }

    [Test]
    public void Can_Get_List_Of_States_In_Country()
    {

        const int countryId = 1;
        //Setup
        geographicsRepository.Setup(x => x.GetStates()).Returns(getStates());

        //Call
        var states = geoService.GetStatesInCountry(countryId);

        //Assert
        Assert.IsInstanceOf<LazyList<State>>(states);
        //How do I write an Assert here to check that the states returned has CountryId = countryId?
        geographicsRepository.VerifyAll();
    }

我需要验证返回状态的信息。我是否需要编写一个循环并将断言放入其中?

2 个答案:

答案 0 :(得分:3)

Assert.IsTrue(states.All(x =&gt; 1 == x.CountryId));

答案 1 :(得分:1)

我不知道nunit中是否有这样的东西,但你可以用linq做到这一点:

    states.All(c => Assert.AreEqual(1, c.CountryId))

修改 快速谷歌搜索后,你似乎可以这样做

Assert.That(states.Select(c => c.CountryId), Is.All.EqualTo(1));