test void simple method with spock - groovy

I have the following method need to be tested:
class Person {
String getFileName(String number) {
return "file"+number
}
void updateSpec(String number) {
new File(getFileName(number)).delete()
}
}
I try to create the testcase like this:
def "update spec"() {
given:
Person person = new Person()
when:
person.updateSpec('1')
then:
1 * File.delete()
}
it says:
Too few invocations for:
1 * File.delete() (0 invocations)
what is the problem and how to fix it, thanks!
And is there a good way to test this method?

Depends on what do you want to test. At first you have to use Mock or Spy to be able to test invocation count.
For example you can test if getFileName() method was called from updateSpec() method and if it was called with '1' argument like this:
def "update spec"() {
given:
Person person = Spy(Person)
when:
person.updateSpec('1')
then:
1 * person.getFileName('1')
}
If you really need to test whether the File.delete() was called, then it will be better to change Person class little bit, because you need File mock on which you can check the invocation count:
class Person {
File getFile(String number) {
return new File("file" + number)
}
void updateSpec(String number) {
getFile(number).delete()
}
}
And the test can be then:
def "File delete was called"() {
given:
File file = Mock(File)
Person person = Spy(Person)
person.getFile(_) >> file
when:
person.updateSpec('1')
then:
1 * file.delete()
}
Another option will be to inject some FileService, wich will encapsulate the File.delete() method, into the Person class and test invoication on it.

You can only define interactions between the object under specification and its mocked dependencies. In your example, however, you are "specifying" an interaction with File class, not mock object. See Spock's Interaction Based Testing. Technically, you can achieve/change your goal as suggested in #cgrim answer. Or you can use tools such as PowerMock (w/o Spock) to mock almost everything but REMEMBER, this kind of technique should only be taken as a last resort. Basically, if you adhere to best design practices then you will never need such tools. Unless you have to deal with some legacy code

Related

Stubbed method should return value depending on given mock parameter in Spock

I would like to have different returning results - depending on the given mocked parameter of a method. Please consider the following code snippet to follow my intention
class ExampleSpec extends Specification {
def "should return second value of list of return values"() {
given:
Person personBob = Mock()
Person personJackson = Mock()
PersonHelper stubbedPerson = Stub()
stubbedPerson.getNameOfBrother(personBob) >> "Billy Bob";
stubbedPerson.getNameOfBrother(personJackson) >> "Tommy Jackson";
when:
String actual = stubbedPerson.getNameOfBrother(personBob)
String actual2 = stubbedPerson.getNameOfBrother(personJackson)
then:
actual == "Billy Bob" // true
actual2 == "Tommy Jackson" // false "Billy Bob"
}
}
The test fails because the second call for var actual2 still return Billy Bob rather than Tommy Jackson. I know there is a way to return different values by call order but I would like to make it dependend on given mocks.
Using normal values - no Mock/Stub Proxies - as parameter values does actually work. I assume that the Spock engine can not differ between two mocks. But I am unsure about this, because the proxies do have IDs as instance fields.
For the record - stubbing with mock objects works. I've added simple Person and PersonHelper classes to your example and the test passes:
import spock.lang.Specification
class ExampleSpec extends Specification {
def "should return second value of list of return values"() {
given:
Person personBob = Mock()
Person personJackson = Mock()
PersonHelper stubbedPerson = Stub()
stubbedPerson.getNameOfBrother(personBob) >> "Billy Bob";
stubbedPerson.getNameOfBrother(personJackson) >> "Tommy Jackson";
when:
String actual = stubbedPerson.getNameOfBrother(personBob)
String actual2 = stubbedPerson.getNameOfBrother(personJackson)
then:
actual == "Billy Bob" // true
actual2 == "Tommy Jackson" // false "Billy Bob"
}
static class Person {
String name
}
static class PersonHelper {
String getNameOfBrother(Person person) {
return null
}
}
}
I have checked it with spock-core:1.1-groovy-2.4, spock-core:1.0-groovy-2.4 and even spock-core:0.7-groovy-2.0. All worked.
But what is even more important - such test does not make any sense. You don't test your code at all. You only test if mocking framework mocks correctly. This test could make some sense if you use Spock mocks in your production code, but this is not a valid assumption.
What may go wrong?
Think for a second about this test. According to your when: block you are trying to test if PersonHelper.getNameOfBrother(Person person) returns a valid name of a brother for two different objects. Now let's assume that this is the only test of a PersonHelper class in your project. Imagine what happens if suddenly implementation of getNameOfBrother method starts throwing NullPointerException for some random reason. Ask yourself - does your unit test protects you from such situation? Nope. Your test always passes, because you are stubbing the method you are testing. If you test a real implementation instead and you pass a real Person object then you will get notified about NullPointerException in the test. Otherwise you will see it when you deploy your code and some user's action calls this method and it fails.

Defining Spock mock behaviors

I am writing my first Spock test and read the docs on mocking interactions, but am still not seeing the "forest through the trees" on a few items.
I have a class, MyRealm, that performs authentication for my app. It has two dependencies, AuthService and ShiroAdapter. The former I'd like to mock and the latter I want to leave as-is (if at all possible). This is because the AuthService actually makes a backend connection to LDAP, so I want to mock it. But the ShiroAdapter just defines several utility methods that convert my objects into Apache Shiro security objects (principals, permissions, etc.). So it can be left un-mocked (methinks).
class MyRealmSpec extends Specification {
MyRealm realm
def setup() {
AuthService authService = Mock(AuthService)
// configure 'authService' mock <-- ?????
ShiroAdapter shiroAdapter = new ShiroAdapter()
realm = new MyRealm(authService: authService,
shiroAdapter: shiroAdapter)
}
def "authenticate throws ShiroException whenever auth fails"() {
when:
realm.authenticate('invalid_username', 'invalid_password')
then:
Throwable throwable = thrown()
ShiroException.isAssignableFrom(throwable)
}
}
I believe I'm very close, but am struggling to configure the mock to behave the way I want it to for the test. The Spock docs (linked above) only seem to document how to verify the number of times a mock method is called. I'm not interested in that here.
Here, MyRealm#authenticate(String,String) calls AuthService#doAuth(String,String) under the hood. So I need my mock AuthService instance to simply either return false (indicating failed auth) or to throw an ServiceFaulException if something unexpected happened.
Any ideas how I can accomplish this?
You are very close, an easy, short-hand way to check a thrown exception type is to put the Exception class in parenthesis. Ex:
def "authenticate throws ShiroException whenever auth fails"() {
when:
realm.authenticate('invalid_username', 'invalid_password')
then:
thrown(ShiroException)
}
You also need to mock the LDAP service call itself and simulate an exception or a failed login. The mock operations go in the then clause of your test.
def "authenticate throws ShiroException whenever auth fails"() {
setup:
String invalidUserName = 'invalid_username'
String invalidPassword = 'invalid_password'
when:
realm.authenticate(invalidUserName, invalidPassword)
then:
1 * authService.doAuth(invalidUserName, invalidPassword) >> returnClosure
thrown(ShiroException)
where:
returnClosure << [{throw new ShiroException()}, { false }]
}
Note that you will need to have the arguments on the mock statements match or use wild card matching.
To match on any String you can use the underscore syntax:
1 * authService.doAuth(_, _) >> false
There are a few different behavior objects you might be interested in.
Stub - You only define what gets returned
MyObject obj = Stub{method >> null}
Mocks - You define what gets returned and/or how many times a method is called
MyObject obj = Mock {1..3 methodCall >> false}
Spies - It creates your object but you can override specific methods as a mock (and your overrides can still make calls to the original code)
MyObject obj = Spy {methodCall >> false}
obj.otherMethodCall() // Calls code like normal
obj.methodCall() // Returns false like we told it to
It sounds like you need a stub, but you could use a mock without any issue. I mention spy, because it's a life-saver if your object ever is self dependent (in the future).
def "authenticate throws ShiroException whenever auth fails"() {
given:
AuthService authService = Stub(AuthService)
authService.doAuth(_,_) >> expectedError
MyRealm realm = new MyRealm(
authService: authService,
shiroAdapter: new ShiroAdapter())
when:
realm.authenticate("just enough to get", "to the doAuth method")
then:
thrown(ShiroException)
where:
expectedError << [ShiroException, /*other exceptions this method has to test*/]
}
The data/logic separation isn't needed, but it's a good approach for making tests more flexible and maintainable. Although in this case it's not really needed since you only have one exception to throw.
I would actually separate your failed authentication and exception-ed authentication tests. They're looking at fundamentally different behaviors and the test logic to test both situations is somewhat different. In the interest of maintainability/flexibility, it's in your interest to avoid testing too much (or too little) with each test.
def "authenticate throws ShiroException whenever auth fails"() {
given:
AuthService authService = Stub(AuthService)
authService.doAuth(_,_) >> { args ->
return args[0] == good && args[1] == good
}
MyRealm realm = new MyRealm(
authService: authService,
shiroAdapter: new ShiroAdapter())
expect:
realm.authenticate(username, password) == expectedAuthentication
where:
userName | password | expectedAuthentication
bad | good | false
bad | bad | false
good | good | true
}
Note on the above test, this tests...
The mock's computation for a return value (testing the test)
Any code that happens between calling authenticate and doAuth()
Hopefully that's what you intend. If there's nothing in .authenticate()'s logic that could break (it has complexity on par with a getter or setter method), this test is mostly a waste of time. The only way that logic could break is if something went wrong in the JVM (which is completely outside the responsibility of this test), or someone made a change sometime in the future (ok, even under the huge assumption that .authenticate() contains unbreakably basic logic the test has some value). My rambling off-topic point (terribly sorry); make sure to keep the what & why of your tests in mind. It will help you prioritize test cases and while working out the best ways to organize/separate test logic.

Grails Spring Security get assigned roles to a method

I would like to have a test that goes through all methods available in a controller and retrieves roles associated with these methods. I understand that it should be a functional test (as opposed to a unit test), but I still do not know how to request the list of roles associated with a method.
Let's say I have this controller:
#Secured("hasAnyRole('ROLE_1')"
class MyController {
def methodA() {}
#Secured("hasAnyRole('ROLE_2')"
def methodB() {}
}
In my test I would like to have something like this:
assertEquals(['ROLE_1'],getRoles(MyController.class, "methodA"))
assertEquals(['ROLE_1', 'ROLE_2'],getRoles(MyController.class, "methodB"))
Any suggestions?
Thanks.
You can do this with the Reflection API. Something like:
Method m = MyController.class.getMethod("methodB");
Annotation[] annos = m.getAnnotations();
But I don't think that's a good validation for your method, since it only ensure that you write the role name correctly. I think it's better you try to call the action and check if the process redirect to denied.
#TestFor(MyController)
class MyControllerTests {
#Test
void shouldRedirectToDenied() {
SpringSecurityUtils.doWithAuth('username') {
controller.methodB()
assert controller.response.redirectedUrl == '/login/denied'
}
}
}
The doWithAuth closure will mock an authentication for the username, so it's the same to say: "do this code as if the username was logged in successfully".
It seems that you will need to use functional tests indeed. See Burt's comment. I'm still think that's not a valid effort create a test only to validate if the method have the annotation.

AssertWasCalled on method in SystemUnderTest

I'm getting into TDD; using nUnit and RhinoMocks 3.5.
I'm trying to figure out how to AssertWasCalled on a method in the SystemUnderTest (SUT). My understanding is that you can't mock the system under test. In fact, my current test results in an exception because the I'm using the AssertWasCalled on the SUT.
OrdersPresenter:
public void OnViewLoad_GetOrders()
{
var orders = GetOrders();
View.Model.Orders = orders;
}
public List<Orders> GetOrders()
{
return _ordersRepository.GetAll();
}
OrdersPresenterTest:
_ordersPresenter = new OrdersPresenter(_view, _ordersRepository);
[Test]
public void OnViewLoad_GetOrders_Should_Call_GetOrders()
{
_view.Raise(v => v.LoadOrders += _ordersPresenter.OnViewLoad_GetOrders, view, new EventArgs);
_ordersPresenter.AssertWasCalled(d => d.GetOrders); // Getting non-mock exception here
}
How do I Assert GetOrders was called in the SUT? I haven't been able to figure it out in the docs.
Any help is greatly appreciated.
Edit:
I understand the GetOrders method in the SUT should be private. I went back thru Roy Osherove's Art of Unit Testing to see how to test private methods. Roy says making a method public (to test against) is not necessarily a bad thing, so I will keep it public.
So I've written a test for GetOrders and I assert the return value ShouldBe a list of orders. That said, I believe I need to restructure my test for OnViewLoad_GetOrders by stubbing the value I get from GetOrders and asserting the results of my actions on that object.
Can someone confirm and explain?
You can not use AssertWasCalled() on not-mocked objects. Just abstract class OrdersPresenter by an interface (use Extract Interface refactoring technique) and then
var ordersPresenter = MockRepository.GenerateMock<IOrderRepository>();
view.Raise(...);
_ordersPresenter.AssertWasCalled(d => d.GetOrders);
BTW,
for me it is not clear why RhinoMocks not used generic parameter constraint for AssertWasCalled
public static void AssertWasCalled<T>(this T mock, Action<T> action,
Action<IMethodOptions<object>> setupConstraints)
Basically T is not limited, but I believe it would be better limit it to somethign like IMockMarkerInterface

how to retrieve nested properties in groovy

I'm wondering what is the best way to retrieve nested properties in Groovy, taking a given Object and arbitrary "property" String. I would like to something like this:
someGroovyObject.getProperty("property1.property2")
I've had a hard time finding an example of others wanting to do this, so maybe I'm not understanding some basic Groovy concept. It seems like there must be some elegant way to do this.
As reference, there is a feature in Wicket that is exactly what I'm looking for, called the PropertyResolver:
http://wicket.apache.org/apidocs/1.4/org/apache/wicket/util/lang/PropertyResolver.html
Any hints would be appreciated!
I don't know if Groovy has a built-in way to do this, but here are 2 solutions. Run this code in the Groovy Console to test it.
def getProperty(object, String property) {
property.tokenize('.').inject object, {obj, prop ->
obj[prop]
}
}
// Define some classes to use in the test
class Name {
String first
String second
}
class Person {
Name name
}
// Create an object to use in the test
Person person = new Person(name: new Name(first: 'Joe', second: 'Bloggs'))
// Run the test
assert 'Joe' == getProperty(person, 'name.first')
/////////////////////////////////////////
// Alternative Implementation
/////////////////////////////////////////
def evalProperty(object, String property) {
Eval.x(object, 'x.' + property)
}
// Test the alternative implementation
assert 'Bloggs' == evalProperty(person, 'name.second')
Groovy Beans let you access fields directly. You do not have to define getter/setter methods. They get generated for you. Whenever you access a bean property the getter/setter method is called internally. You can bypass this behavior by using the .# operator. See the following example:
class Person {
String name
Address address
List<Account> accounts = []
}
class Address {
String street
Integer zip
}
class Account {
String bankName
Long balance
}
def person = new Person(name: 'Richardson Heights', address: new Address(street: 'Baker Street', zip: 22222))
person.accounts << new Account(bankName: 'BOA', balance: 450)
person.accounts << new Account(bankName: 'CitiBank', balance: 300)
If you are not dealing with collections you can simply just call the field you want to access.
assert 'Richardson Heights' == person.name
assert 'Baker Street' == person.address.street
assert 22222 == person.address.zip
If you want to access a field within a collection you have to select the element:
assert 'BOA' == person.accounts[0].bankName
assert 300 == person.accounts[1].balance​​​​​​​​​
You can also use propertyMissing. This is what you might call Groovy's built-in method.
Declare this in your class:
def propertyMissing(String name) {
if (name.contains(".")) {
def (String propertyname, String subproperty) = name.tokenize(".")
if (this.hasProperty(propertyname) && this."$propertyname".hasProperty(subproperty)) {
return this."$propertyname"."$subproperty"
}
}
}
Then refer to your properties as desired:
def properties = "property1.property2"
assert someGroovyObject."$properties" == someValue
This is automatically recursive, and you don't have to explicitly call a method. This is only a getter, but you can define a second version with parameters to make a setter as well.
The downside is that, as far as I can tell, you can only define one version of propertyMissing, so you have to decide if dynamic path navigation is what you want to use it for.
See
https://stackoverflow.com/a/15632027/2015517
It uses ${} syntax that can be used as part of GString

Resources