gilliduck
gilliduck

Reputation: 2918

Asserting a property has been set in a mocked class

I'm using the MockingContainer<T> to automatically set up my dependencies. How do I assert that a property on one of those dependencies gets set?

[SetUp]
public void SetUp()
{
    //arrange
    _baseUrl = "http://baseUrl";
    _container = new MockingContainer<ApiInteractionService>();
    _container.Arrange<IConfigService>(m => m.BaseUrl).Returns(_baseUrl);
    _uut = _container.Instance;
}

The following fails with 0 calls, which makes sense since I believe it's looking at the Getter, not the Setter. So how do I assert that the Setter was called by the unit under test?

[Test]
public void BaseUrlSet()
{
    //act
    var _ = _uut.MakeRequest((InitialRequest) Arg.AnyObject);

    //assert     
    _container.Assert<IRestService>(m => m.BaseUrl, Occurs.Once());
}

Per the documentation (located at JustMock Docs for anyone who isn't familiar but wishes to try assisting) it appears I should be using Mock.ArrangeSet(lambda), however I cannot seem to figure out how to get that syntax to work in relation to MockingContainer<T>.

If worse comes to worse, I can just NOT use MockingContainer<T>, but I'd prefer to not have to refactor my test suite just to accommodate one specific unit test.


Not that it's really relevant to the question, but in the off chance anyone needs it, here is a stub of ApiInteractionService

public ApiInteractionService(IRestService restService, IConfigService configService)
{
    _restService = restService;
    _restService.BaseUrl = configService.BaseUrl;
}

public string MakeRequest(InitialRequest initialRequest)
{
    return _restService.Post(initialRequest);
}

Upvotes: 1

Views: 214

Answers (1)

Stefan Dragnev
Stefan Dragnev

Reputation: 14473

Why not simply assert that BaseUrl has the correct value at the end of the test?

var baseUrl = _container.Get<IRestService>().BaseUrl;
Assert.AreEqual(baseUrl, _baseUrl);

As suggested in the comments, _container.Assert<IRestService>(m => m.BaseUrl == _baseUrl) will not work. MockingContainer<T>.Assert asserts an expectation, it's not just asserting truth like regular asserts. The correct syntax would have been:

_container.AssertSet<IRestService>(restService => restService.BaseUrl = _baseUrl, Occurs.Once());

but, oddly, there is no AssertSet method on the container.

Upvotes: 0

Related Questions