Unit tests with mock verifies - nunit

I have a unit test that
creates a mock
calls my method to be tested (also injecting my mock)
asserts method results
verifies mock calls
When mock calls don't verify as expected I get an exception, thus failing a test.
How should I correctly call this verifies? Should I just be calling
// verify property get accessor call
m.VerifyGet<bool>(p => p.IsRead, Times.AtLeastOnce());
or should I call it with Assert
// verify property get accessor call
Assert.DoesNotThrow(() => m.VerifyGet<bool>(p => p.IsRead, Times.AtLeastOnce()));
When verify fails I get an exception anyway.
What's the proper way of mock verifying?

VerifyGet is enough, assert seems to add no value so why add more verbiage?

The DoesNotThrow-method should be used to test whether your own methods adhere to your specifications.
In short, adding the DoesNotThrow looks like you're testing the behaviour of VerifyGet instead of the behaviour of your SUT.
Of course, you can wrap it around the VerifyGet, but I think that only makes things confusing since VerifyGet would fail the test anyway.

Related

Akka-http logging request identifier

I've been using akka-http for a while now, and so far I've mostly logged things using scala-logging by extending either StrictLogging or LazyLogging and then calling the:
log.info
log.debug
....
This is kinda ok, but its hard to understand which logs were generated for which request.
As solutions for this go, I've only seen:
adding an implicit logging context that gets passed around (this is kinda verbose and would force me to add this context to all method calls) + custom logger that adds the context info to the logging message.
using the MDC and a custom dispatcher; in order to implement this approach one would have to use the prepare() call which has just been deprecated.
using AspectJ
Are there any other solutions that are more straightforward and less verbose ? It would be ok to change the logging library btw..
Personally I would go with implicit context approach. I'd start with:
(path("api" / "test") & get) {
val context = generateContext
action(requestId)
}
Then I'd would make it implicit:
(path("api" / "test") & get) {
implicit val context = generateContext
action
}
Then I would make the context generation a directive, like e.g.:
val withContext: Directive1[MyContext] = Directive[Tuple1[MyContext]] {
inner => ctx => inner(Tuple1(generateContext))(ctx)
}
withContext { implicit context =>
(path("api" / "test") & get) {
action
}
}
Of course, you would have to take context as an implicit parameter to every action. But, it would have some advantages over MDC and AspectJ - it would be easier to test things, as you just need to pass value. Besides, who said you only ever need to pass request id and use it for logging? The context could as well pass data about logged in user, its entitlements and other things that you could resolve once, use even before calling action and reuse inside action.
As you probably guessed, this would not work if you want the ability to e.g. remove logging completely. In such case AspectJ would make more sense.
I would have most doubts with MDC. If I understand correctly it has build in assumption that all logic would happen in the same thread. If you are using Futures or Tasks, could you actually guarantee such thing? I would expect that at best all logging calls would happen in the same thread pool, but not necessarily the same thread.
Bottom line is, all possible posiltions would be some variant of what you already figured out, so the question is your exact use case.

Why is this Autofac mock's lifetime disposed in a simple MSpec test?

I've got a base class I'm using with MSpec which provides convenience methods around AutoMock:
public abstract class SubjectBuilderContext
{
static AutoMock _container;
protected static ISubjectBuilderConfigurationContext<T> BuildSubject<T>()
{
_container = AutoMock.GetLoose();
return new SubjectBuilderConfigurationContext<T>(_container);
}
protected static Mock<TDouble> GetMock<TDouble>()
where TDouble : class
{
return _container.Mock<TDouble>();
}
}
Occasionally, I'm seeing an exception happen when attempting to retrieve a Mock like so:
It should_store_the_receipt = () => GetMock<IFileService>().Verify(f => f.SaveFileAsync(Moq.It.IsAny<byte[]>(), Moq.It.IsAny<string>()), Times.Once());
Here's the exception:
System.ObjectDisposedExceptionInstances cannot be resolved and nested
lifetimes cannot be created from this LifetimeScope as it has already
been disposed.
I'm guessing it has something to do with the way MSpec runs the tests (via reflection) and that there's a period of time when nothing actively has references to any of the objects in the underlying lifetime scope being used by AutoMock which causes the lifetimescope to get disposed. What's going on here, and is there some simple way for me to keep it from happening?
The AutoMock lifetime scope from Autofac.Extras.Moq is disposed when the mock itself is disposed. If you're getting this, it means the AutoMock instance has been disposed or has otherwise lost scope and the GC has cleaned it up.
Given that, there are a few possibilities.
The first possibility is that you've got some potential threading challenges around async method calls. Looking at the method that's being mocked, I see you're verifying the call to a SaveFileAsync method. However, I don't see any async related code in there, and I'm not entirely sure when/how the tests running are calling it given the currently posted code, but if there is a situation where an async call causes the test to run on one thread while the AutoMock loses scope or otherwise gets killed on the other thread, I could see this happening.
The second possibility is the mix of static and instance items in the context. You are storing the AutoMock as a static, but it appears the context class in which it resides is a base class that is intended to supply instance-related values. If two tests run in parallel, for example, the first test will set the AutoMock to what it thinks it needs, then the second test will overwrite the AutoMock and the first will go out of scope, disposing the scope.
The third possibility is multiple calls to BuildSubject<T> in one test. The call to BuildSubject<T> initializes the AutoMock. If you call that multiple times in one test, despite changing the T type, you'll be stomping the AutoMock each time and the associated lifetime scope will be disposed.
The fourth possibility is a test ordering problem. If you only see it sometimes but not other times, it could be that certain tests inadvertently assume that some setup, like the call to BuildSubject<T>, has already been done; while other tests may not make that assumption and will call BuildSubject<T> themselves. Depending on the order the tests run, you may sometimes get lucky and not see the exception, but other times you may run into the problem where BuildSubject<T> gets called at just the wrong time and causes you pain.

How to expect on method calls that has inline new instance creations in easymock

We have following code structure in our code
namedParamJdbcTemplate.query(buildMyQuery(request),new MapSqlParameterSource(),myresultSetExtractor);
and
namedParamJdbcTemplate.query(buildMyQuery(request),new BeanPropertySqlParameterSource(mybean),myresultSetExtractor);
How can I expect these method calls without using isA matcher?
Assume that I am passing mybean and myresultSetExtractor in request for the methods in which above code lies.
you can do it this way
Easymock.expect(namedParamJdbcTemplateMock.query(EasyMock.anyObject(String.class),EasyMock.anyObject(Map.class),EasyMock.anyObject(ResultSetExtractor.class))).andReturn(...);
likewise you can do mocking for other Methods as well.
hope this helps!
good luck!
If you can't use PowerMock to tell the constructors to return mock instances, then you'll have to use some form of Matcher.
isA is a good one.
As is anyObject which is suggested in another answer.
If I were you though, I'd be using Captures. A capture is an object that holds the value you provided to a method so that you can later perform assertions on the captured values and check they have the state you wanted. So you could write something like this:
Capture<MapSqlParameterSource> captureMyInput = new Capture<MapSqlParameterSource>();
//I'm not entirely sure of the types you're using, but the important one is the capture method
Easymock.expect(namedParamJdbcTemplateMock.query(
EasyMock.anyObject(Query.class), EasyMock.capture(captureMyInput), EasyMock.eq(myresultSetExtractor.class))).andReturn(...);
MapSqlParameterSource caughtValue = captureMyInput.getValue();
//Then perform your assertions on the state of your caught value.
There are lots of examples floating around for how captures work, but this blog post is a decent example.

How to perform a custom check of the arguments being passed to mockito mocks

I have a problem writing tests for scala project using specs2 and mockito.
Is there a way to perform some complex checks for arguments that was passed by a method being tested to a mocked service method? For example:
session = ....
sessionDao.getByUid(sessionUID).returns(Some(session))
val result = service.refreshSessionFor(token)
result must beLeft
got{
one(sessionDao).getByUid(sessionUID)
one(sessionDao).update(any[Session])
}
The problem is, i want to check whether field "lastUsed" of session object was updated or not. The only way is to check parameter fields of the sessionDao.update method. But I cannot find how to do this in the mockito manual.
You can pass any specs2 matcher to a mocked method:
got{
one(sessionDao).getByUid(sessionUID)
one(sessionDao).update(beLike[Session] { case s: Session => s.lastUsed must be_>(last) })
}

Model is not automatically validated when unit testing

Here's part of a controller action:
[HttpPost]
public ActionResult NewComplaint(Complaint complaint)
{
if(!ModelState.IsValid)
{
// some code
}
// some more code...
}
When running the application, the model is automatically validated before the if statement is even called. However, when attempting to unit test this code, the automatic validation does not occur.
If I were to use a FormCollection and call TryUpdateModel instead, the validation would occur but I don't want to use that.
I've found that calling TryValidateModel(model) before the if statement works around the problem well; only requiring one extra line of code. I'd rather get rid of it however.
Any ideas why the automatic validation does not occur when unit testing but occurs when the application is running?
EDIT: Forgot to mention, I'm using ASP.NET MVC3 RC1 and I'm mocking the HTTPContext object of the controller if that makes any difference
Validation occurs during model binding (and TryUpdateModel performs model binding).
But I think the problem is that what you are trying to test is the MVC framework (i.e. the fact that validation occurs before an action method is invoked). You shouldn't test that.
You should assumet that that part just works (because we test it extensively) and only test your application code. So in this case, the only thing you need to mock is the return value of ModelState.IsValid and you can do that by adding a validation error manually:
ModelState.AddModelError("some key", "some error message")