@ExpectedException in grails unit tests
Asked Answered
W

1

6

Anyone used this annotation in grails unit tests? Didnt seem to work for me. Thanks. D

Update: the last line of my test below does throw the expected exception. However the test fails (Stack trace too big for here...). I'm using grails 1.2 and running the test in eclipse's junit runner. Maybe grails is using an earlier version of junit than 4?

/**
 * Get the EC by a manager of a different company. Should throw exception
 */
@ExpectedException(ServiceAuthorizationException.class)
void testGetEcByNonOwnerManagerOfDifferentCompany() {
    mockDomain(ExpenseClaim , [new ExpenseClaim(id:"1",narrative:"marksClaim", employee:userMark, company:dereksCompany)])      

    def authControl = mockFor(AuthenticateService)
    authControl.demand.userDomain(1..1)  {-> otherUserMgr }
    authControl.demand.ifAllGranted(1..1)  {String arg1 -> return "ROLE_COMPANYMANAGER".equals(arg1) } //returns true
    def testService = new ExpenseClaimService()
    testService.authenticateService = authControl.createMock()
    def thrown = false
    testService.getExpenseClaim("1")
}
Waugh answered 30/12, 2009 at 20:59 Comment(3)
Can you explain what you mean by "didn't work"?Autoharp
Hi John, Thanks for the help. Yes I'm lacking a bit of detail there.... I'll add a reply as I cant fit it in this comment box. DWaugh
Ah yes its using junit 3.4.2. I think this only works with junit4. I think this is the answerWaugh
T
17

Only JUnit 3 is currently supported, so use shouldFail() instead:

void testGetEcByNonOwnerManagerOfDifferentCompany() {

  shouldFail(ServiceAuthorizationException) {
    mockDomain(ExpenseClaim , [new ExpenseClaim(id:"1",
                               narrative:"marksClaim", employee:userMark,
                               company:dereksCompany)])      

    def authControl = mockFor(AuthenticateService)
    authControl.demand.userDomain(1..1)  {-> otherUserMgr }
    authControl.demand.ifAllGranted(1..1)  {String arg1 ->
       "ROLE_COMPANYMANAGER".equals(arg1) } //returns true
    def testService = new ExpenseClaimService()
    testService.authenticateService = authControl.createMock()
    testService.getExpenseClaim("1")
  }
}

shouldFail() is actually more convenient since you can use it more than once per test, and it returns the exception message so you can assert based on the message as well as the exception.

Traipse answered 30/12, 2009 at 23:38 Comment(3)
is this still applicable as of 1.3.7 ?Karlotta
As of 2.0 you can use JUnit 4, but as I said I'd still use shouldFail since it's so flexible.Traipse
Not to troll this question, but I found the answer helpful with a small change. In my opinion, you should only wrap the code under test in the shouldFail(){} block. Because if any of the buildup for the test fails, this test will be green and give you a false positive.Cassandry

© 2022 - 2024 — McMap. All rights reserved.