Posts

Showing posts with the label Mocking

Assert A Function/method Was Not Called Using Mock

Answer : This should work for your case; assert not my_var.called, 'method should not have been called' Sample; >>> mock=Mock() >>> mock.a() <Mock name='mock.a()' id='4349129872'> >>> assert not mock.b.called, 'b was called and should not have been' >>> assert not mock.a.called, 'a was called and should not have been' Traceback (most recent call last): File "<stdin>", line 1, in <module> AssertionError: a was called and should not have been Though an old question, I would like to add that currently mock library (backport of unittest.mock) supports assert_not_called method. Just upgrade yours; pip install mock --upgrade You can check the called attribute, but if your assertion fails, the next thing you'll want to know is something about the unexpected call, so you may as well arrange for that information to be displayed from the start. Using unittest , you can...

Check If A Property Was Set - Using Moq

Answer : I think VerifySet is the right approach. It would look something like this: //Arrange var mock = new Mock<IDRepository>(); var mockRequest = new Mock<Request>(); // TODO: set some expectations here var dManager = new DManager(mock.Object); //Act dManager.Create(mockRequest.Object); //Assert mockRequest.VerifySet(x => x.Status = Status.Submitted); I believe in your case, it blows up because you haven't set up your Request mock to handle the set operation on Status. One easy way to do that is using SetupAllProperties , like so: //Arrange var mock = new Mock<IDRepository>(); var mockRequest = new Mock<Request>(); mockRequest.SetupAllProperties(); I think you should use strict behavior by default, then you can make the verification with a single call. It also makes you write your test more explicitly. [TestMethod] public void AddingNewRequestSetsStatusToSubmitted() { //Arrange var mock = new Mock<IDRepository>(MockBehav...