The method expect(boolean) is undefined for the type in Shiro test - testing

I'm doing my first test in Java, and I have a Shiro Security... I follow the tutorial (https://shiro.apache.org/testing.html) but says:
(this example uses EasyMock, but Mockito works equally as well):
Subject subjectUnderTest = createNiceMock(Subject.class);
expect(subjectUnderTest.isAuthenticated()).andReturn(true);
Because I use Mockito I implement with
Subject mockSubject = mock(Subject.class);
expect(subjectUnderTest.isAuthenticated()).andReturn(true);
But when I do it have this error
The method expect(boolean) is undefined for the type AdminControllerTest
And don't give me the posibility to import it. I don't know if expect is especific of EasyMock and if yes what I have to use in Mockito.
I search here and see more person doing it and always recomend use this expect
How to mock a shirosession?

If we look at this code example ...
Subject mockSubject = mock(Subject.class);
expect(subjectUnderTest.isAuthenticated()).andReturn(true);
We can see that ...
You are using mockito syntax to do the mocking.
You are using easyMock syntax to configure the mock. It is not even in the dependency list, so this method is not found.
The solution is to use mockito syntax to configure the mock.
Subject mockSubject = mock(Subject.class);
when(mockSubject.isAuthenticated()).thenReturn(true);
This will make everything work as expected and your Subject will return true, when the isAuthenticated() method is called.
If you want to up your mockito game, try this resource, which comes with working github code examples.

Related

How can I mock a call to Spring's repository `saveAll()` method using mockk?

I am using Mockk as my mocking framework when testing my Spring Boot Data repository interfaces.
Actually I am doing the following
every { itemRepository.saveAll(listOf(any(), any())) } returns listOf<Item>(mockk())
which should mock the following behaviour
val loot: List<Item> = itemGenerator.generateLoot(lootTable)
itemRepository.saveAll(loot)
The error message I receive is the following:
Failed matching mocking signature for
SignedCall(retValue=, isRetValueMock=true, retType=class kotlin.collections.Iterable, self=ItemRepository(#28), method=saveAll(Iterable), args=[[com.barbarus.gameserver.item.Item#ea00de, com.barbarus.gameserver.item.Item#23ca36d]], invocationStr=ItemRepository(#28).saveAll([com.barbarus.gameserver.item.Item#ea00de, com.barbarus.gameserver.item.Item#23ca36d]))
left matchers: [any(), any()]
The error message says left matchers: [any(), any()] pointing out that I somehow am not defining the expected arguments right.
I could fully define the items by real implementations in my test logic but I'd like to stick with mockk() just to keep the test code slim and fast.
However I kinda am not able to define the List<Item> with two elements using listOf(any(),any()) here. I tried other API of Mockk without any luck.
Any idea what to use in this case?
You should type the any() when you are passing into saveAll().
For instance:
import com.barbarus.gameserver.item.Item
...
every { itemRepository.saveAll(any<List<Item>>() } returns listOf<Item>(mockk())
Solution from another post

What is the purpose, and proper use of wantTo() in Codeception?

I'm using the testing framework Codeception to do BDD. I understand the idea of wanting something, but I don't understand what the function does.
$I->wantTo('Understand what this method does!');
http://codeception.com/docs/03-AcceptanceTests#Comments
Commands like amGoingTo, expect, expectTo help you in making tests
more descriptive.
$I->wantTo('Understand what this method does!');
will be rendered as * I want to understand what this method does! in verbose output.
Update 2022-11-16:
My original answer was incorrect, wantTo is not a comment method, it renames test method in the output.
Example:
I created very simple Cest class:
<?php
class ExampleCest
{
public function provideExample(CliGuy $I)
{
}
}
When I ran it, I got the following output:
Cli Tests (1) --------------------------------------------
U ExampleCest: Provide example (0.00s)
---------------------------------------------------------
but after adding $I->wantTo('change test name!'); to method:
I got the following output:
Cli Tests (1) --------------------------------------------
U ExampleCest: Change test name! (0.00s)
---------------------------------------------------------
The benefit of wantTo is that it allows to use characters not permitted in method names or different formatting than automatically generated.
I looked up if wantTo has any documentation and all I found was old blog post using examples in class-less Cept format (which is deprecated and is likely to be removed in Codeception 6).
<?php
$I = new TestGuy($scenario);
$I->wantTo('log in to site');
$I->amOnPage('/');
$I->click('Login');
$I->fillField('username', 'admin');
In Cept format wantTo had better purpose, because it didn't override anything, but provided additional information next to file name.

Spock & Spock Reports: how "catch" and customize the error message for AssertionError?

I am working with:
Spock Core
Spock Reports
Spock Spring
Spring MVC Testing
and I have the following code:
#FailsWith(java.lang.AssertionError.class)
def "findAll() Not Expected"(){
given:
url = PersonaUrlHelper.FINDALL;
when:
resultActions = mockMvc.perform(get(url)).andDo(print())
then:
resultActions.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_XML))
}
Here the code fails (how is expected) because the method being tested really returns (MediaType.APPLICATION_JSON) instead of (MediaType.APPLICATION_XML).
So that the reason of #FailsWith(java.lang.AssertionError.class).
Even if I use #FailsWith(value=java.lang.AssertionError.class, reason="JSON returned ...") I am not able to see the reason through Spock Reports
Question One: how I can see the reason on Spock Reports?.
I know Spock offers the thrown() method, therefore I am able to do:
then:
def e = thrown(IllegalArgumentException)
e.message == "Some expected error message"
println e.message
Sadly thrown does not work for AssertionError.
If I use thrown(AssertionError) the test method does not pass, unique way is through #FailsWith but I am not able to get the error message from AssertionError
Question Two how is possible get the Error Message from AssertionError?
I know I am able to do something like
then: "Something to show on Spock Reports"
But just curious if the question two can be resolved..
regarding Question one:
if you look at FailsWithExtension#visitFeatureAnnotation you can see that only value from the #FailsWith is evaluated, reason is not touched at all. What you could do is introduce you own type of annotation (custom one, e.g. same as #FailsWith) and override AbstractAnnotationDrivenExtension#visitFeatureAnnotation. There you have access to reason parameter.
regarding Question two:
please look at this link: http://spock-framework.3207229.n2.nabble.com/Validate-exception-message-with-FailsWith-td7573288.html
additionally maybe you could override AbstractAnnotationDrivenExtension#visitSpec and add custom listener (overriding AbstractRunListener). Then you have access to AbstractRunListener#error method whose documentation says:
Called for every error that occurs during a spec run. May be called multiple times for the same method, for example if both
* the expect-block and the cleanup-block of a feature method fail.
Didn't test for Question two, but it may work. I've used sth similar.
Enjoy,
Tommy

How can you use SessionAsSigner in a Java Bean called from an XPage?

According to Phillip Riand (see: discussion on openNTF) this is not possible... They need to know the design element to find out who signed it. Therefore, it is only available in SSJS.
There are 2 ways that I know of to use the sessionAsSigner object in Java beans:
1 By resolving the sessionAsSigner object:
FacesContext context = FacesContext.getCurrentInstance();
Session sessionAsSigner = context.getApplication().getVariableResolver().
resolveVariable(context, "sessionAsSigner");
2 By using the getCurrentSessionAsSigner() function from the com.ibm.xsp.extlib.util.ExtLibUtil class in the Extension Library.
To be able to use it (in Java as wel as SSJS) you'll want to make sure that all design elements were signed by the same user ID. If that's not the case, the sessionAsSigner object will not be available ('undefined').
I found that the solution is right at hand :-)
I changed my XPage (in this example an XAgent) to:
<xp:view xmlns:xp="http://www.ibm.com/xsp/core" rendered="false">
This is an xAgent returning json data...
<xp:this.afterRenderResponse><![CDATA[#{javascript:Controller.verify(sessionAsSigner)}]]></xp:this.afterRenderResponse>
and in the bean I simply used the session in the argument when I needed to open a database/document as signer. Sometimes the solution is so simple :-)
/John
This is quite an old post that I just stumbled upon. Tried some of the solutions mentioned above:
resolveVariable did not work for me, at least not for sessionAsSigner as this throws a runtime error (I can resolve plain old session, though...)
to be honest I didn't quite understand the Controller.verify(sessionAsSigner) method; is Controller something specific to XAgents? If so, I don't have an XAgent here, so can't use it
didn't feel like importing extra ExtLib classes here...
So I came up with another solution that appears to be very simple:
created a method in my javaBean that takes a session object as argument; since sessionAsSigner belongs to the same class as session I don't have to import something new.
Javacode is:
public void testSession(Session s) throws Exception{
System.out.println(" > test effective user for this session = "
+ s.getEffectiveUserName());
}
This is called from SSJS as either
mybean.testSession(session);
or
myBean.testSession(sessionAsSigner);
Maybe helps others, too

Difference in Behavior between Rhino and FakeItEasy

We're considering switching from Rhino to FakeItEasy for our mocking framework. The main reason is simplicity, in FakeItEasy there's only one way to do things. Rhino has record/playback, AAA, stub, partial mock, strict mock, dynamic mock, etc.
I'm rewriting some of our tests using FakeItEasy to ensure it will do everything Rhino is currently doing for us, and I've encountered something I can't explain and was hoping someone could enlighten me.
In Rhino, I have the following test. The code has been abbreviated.
ConfigurationManagerBase configManager = _mocks.Stub<ConfigurationManagerBase>();
using( _mocks.Record() )
{
SetupResult
.For( configManager.AppSettings["ServerVersion"] )
.Return( "foo" );
}
The unit test to which this code is attached runs just fine and the test passes. I rewrote it using FakeItEasy as follows.
ConfigurationManagerBase configManager = A.Fake<ConfigurationManagerBase>();
A.CallTo( () => configManager.AppSettings["ServerVersion"] )
.Returns( "foo" );
Now when I run the test it fails, but it's because FakeItEasy is throwing an exception.
The current proxy generator can not intercept the specified method for the following reason:
- Non virtual methods can not be intercepted.
That seemed odd, because Rhino has the same restriction. What we think is happening in that while AppSettings is virtual on ConfigurationManagerBase, the indexer property is not. We corrected the problem by changing the FakeItEasy test to read.
NameValueCollection collection = new NameValueCollection();
collection.Add( "ServerVersion", "foo" );
A.CallTo( () => configManager.AppSettings )
.Returns( collection );
I'm basically just trying to understand whether I'm doing something wrong with FakeItEasy or is Rhino performing some "magic" behind the scenes with that indexer?
The following configuration should be similar to what Rhino does if this doesn't work Rhino does something magic:
NextCall.To(configManager.AppSettings).Returns("foo");
var ignored = configManager.AppSettings["ServerVersion"];