how to test play!'s controller annotated with #With annotation? - unit-testing

I use interceptor annotated #With(Secure.class) that check access to a controller.
There is some regular logic performed in the controller that i want to test.
However, when i run my test (startTest) it intercepted by Secure that cause the test to fail.
startTest A play.mvc.results.Redirect has been caught, null Hide trace
play.mvc.results.Redirect
Is there any way to avoid redirection?

Related

How to identify a xfail test from pytest_runtest_makereport hook?

Context
We want to emit test result metric in a near to real-time manner. Therefore, we publish metrics from the pytest_runtest_makereport hook. It seems that in the pytest_runtest_makereport hook, the tests that xfailed or xpassed are marked as skipped.
Question
Is there any way that we can identify if a test result is xfailed or xpassed from pytest_runtest_makereport hook?
We could differentiate xfailed and xpassed test from the skipped test from the pytest_terminal_summary hook through terminalreporter object, which offers a way to get a list of test nodeid by the test result. For example:
terminalreporter.stats.get("xfailed", [])
In your pytest_runtest_makereport hook you can use
if call.excinfo and call.excinfo.typename == "XFailed":
to detect a call to pytest.xfail("...") from within the test. If the test was marked with #pytest.mark.xfail("..."), you will have to detect the test failure and then look for the mark (or check the mark earlier and remember it).

Mockito, TooManyActualInvocations when testing conditions Spek Framework

For a scenario unit testing a user entering a password and password confirmation. when i try to verify the same method being called in a different on() block, i get the following error on the 2nd on()block.
org.mockito.exceptions.verification.TooManyActualInvocations:
activationPasswordView.disableButton();
Wanted 1 time:
But was twice
Here is the code:
given("user set password "){
on(“password is null”){
presenterImpl.validatePassword(null, null)
it("done button should be disabled"){
verify(view).disableButton()
}
}
on("input only one password"){
presenterImpl.validatePassword("Password", "")
it("done button should be disabled"){
verify(view).disableButton()
}
}
}
But if i call a different method, it works correctly. I assume this was not how Spek framework was intended to be used as all the examples i have seen always use an Assert. Is there a way i can write the following conditions in Spek without the error?. Even a different given() still causes the error.
The mocked object counts the number of times the function invoked for the specific mock.
Since you did not reset the mock between each test, the counter is increased each time you invoked the method.
You should use: reset(view) to reset the mocks counter.
This issue is not related to the Spek framework.

How does ApiControllerAttribute affect unit test?

In asp.net core 2.1 some new features have been introduced, specifically the ApiControllerAttribute. In combination with the CompatibilityVersion.Version_2_1 there are some changes in behaviour.
One of the changes is that the ModelState test can be omitted. Without ApiControllerAttribute I would need:
public ActionResult DoSomething([FromBody] SomeDto dto)
{
if (!ModelState.IsValid)
return BadRequest();
return Ok("Done");
}
And with ApiControllerAttribute:
public ActionResult DoSomething([FromBody] SomeDto dto)
{
return Ok("Done");
}
Where an invalid dto would automatically result in a BadRequest.
But now for unit tests this doesn't work. If I want to test a controller, then in the previous situation the unit test would fail when an invalid dto was inserted. But in the current situation the ModelState isn't validated, meaning that the test will succeed.
So my question, do I have to use Integration Tests now to test the controllers? Or is there another way to get the same behaviour based on the ApiControllerAttribute?
The ApiControllerAttribute is metadata that is only relevant at run time so that means you will have to use TestServer in an integration test and actually call the action under test for it to be part of the test.
It influences scenarios where unit tests want to manually check model state and model state errors when testing controller actions in isolation.
It does not stop one from still including model state checks in a controller if using custom action filters or from directly returning from the action due to model state errors.
The features provided by the attribute just wont be available in isolated unit tests and tests would need to take that into consideration when it comes to expected behavior when being exercised.

MOQ Unit Test - Assert Vs Verify

Am trying to understand what Exactly Verify or VerifyAll Does ?
I was searching and i got the below info on using MOQ
Arrange
Mock
Set up expectations for dependencies
Set up expected results
Create class under test
Act
Invoke method under test
Assert
Assert actual results match expected results
Verify that expectations were met
So What exactly does Verify Does? I can test everything using Assert and in case if any failures the unit test will fail ?
What extra work does verify does ? Is it the replacement for Assert ?
Some more clarify will make me understand.
Thanks
Assert vs Mock.Verify
Assert is used to do checks on the class/object/subject under test (SUT).
Verify is used to check if the collaborators of the SUT were notified or contacted.
So if you are testing a car object, which has an engine as a collaborator/dependency.
You would use to Assert to see if car.IsHumming after you invoke car.PushStart()
You would use Verify to see if _mockEngine.Ignition() received a call.
Verify vs VerifyAll
Approach One:
Explicitly setup all operations you expect to be triggered on the mocked collaborator from the subsequent Act step
Act - do something that will cause the operations to be triggered
call _mock.VerifyAll() : to cause every expection that you setup in (1) to be verified
Approach Two
Act - do something that will cause the operations to be triggered
call _mock.Verify(m => m.Operation) : cause verification that Operation was in fact called. One Verify call per verification. It also allows you to check count of calls e.g. exactly Once, etc.
So if you have multiple operations on the Mock OR if you need the mocked method to return a value which will be processed, then Setup + Act + VerifyAll is the way to go
If you have a few notifications that you want to be checked, then Verify is easier.

mspec & rhino mocks expected exception testing

I'm fairly new to unit testing and can't get around how to test (or if I even should) this case properly.
I have a controller method (pseudo code):
public ActionResult Register(formModel model)
{
if (ModelState.isValid) {
try {
_userService.CreateUser(a bunch of parameters here);
return RedirectToAction(some other action);
}
catch (Exception e)
{
ModelState.AddModelError("",e.Message);
}
}
return View();
}
I have a bunch of separate tests against "_userService". The "CreateUser" method just creates a new user and returns nothing OR throws an exception if there was an error (ex. the user exists) that I bubble up to the controller surround in a try catch and add the exception to the ModelState.
From what I understand I should mock the service and assert that it was called correctly (i use the assertwascalled syntax) since it returns nothing and I just want to know that my controller calls it.
What I'm not sure is how to test that when the userservice throws an error it should not redirect and should add that exception to the modelstate. With rhino mocks you can stub a mock but the book art of unit testing advises against that.
Right now in my test I manually add a model error (not caring if it's from user service) and test that the controller returns the same view if there are errors. Is this the correct way of going about this? Or should I maybe create a separate test where I stub the _userService to throw an error and check it gets added to modelstate? Or should I not even test that case? I feel like I may be just over analyzing the whole thing and testing using the modelstate would be enough to satisfy this...
Your mock represents a collaborating class. I wouldn't get too hung up on the difference between mocks and stubs; it's still a collaborating class.
You can think of your unit tests as describing how to use your class, and how the class then interacts with its collaborators. You have two examples:
Given a controller
When I register the model
Then the class should ask the user service to create a user.
And:
Given a controller
Given the user service is broken
When I register the model
Then the class should attach the error to the model state.
It's that second Given that tells you you're stubbing rather than mocking. You're setting the user service up as though it's broken. The context in which the class acts is different, so you need to stub, and you should indeed throw an exception.
If you put these lines as comments inside your test, it'll make sense. If it makes sense, ignore the book.
BTW, this is unit-level BDD. You can use "Given, When, Then" at a unit level just as at a scenario level, and it might help you think about the logic of your tests. Just don't use BDD scenario tools for this.