小编Cap*_*ain的帖子

Nullpointer在简单的grails控制器单元测试中

我需要一些奇怪的问题,我正面临单元测试一个非常基本的Grails 2.4.1控制器.

鉴于此控制器:

class AuthenticationEventController {
    def index() {
        // Sorry, ajax only!
        if(!request.xhr) {
            redirect(controller: "main")
            return false
        }

        render(template: "index")
        return
    }
}
Run Code Online (Sandbox Code Playgroud)

而这个测试:

@TestFor(AuthenticationEventController)
class AuthenticationEventControllerSpec extends Specification {

    void "Test that the index rejects non-ajax calls"() {
        given:
            request.isXhr = { false }

        when:
            controller.index()

        then:
            response.redirectedUrl == '/main'
    }
}
Run Code Online (Sandbox Code Playgroud)

我在"controller.index()"调用上得到一个NullPointerException.

java.lang.NullPointerException
    at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:130)
    at org.codehaus.groovy.grails.orm.support.GrailsTransactionTemplate.execute(GrailsTransactionTemplate.groovy:85)
    at au.com.intrinsicminds.advansys.controller.AuthenticationEventControllerSpec.Test that the index rejects non-ajax calls(AuthenticationEventControllerSpec.groovy:17)
Run Code Online (Sandbox Code Playgroud)

grails unit-testing

10
推荐指数
2
解决办法
2657
查看次数

为什么我们不在单元测试中模拟域对象?

我给你 2 个测试;其目的仅仅是确认何时service.doSomething被调用,emailService.sendEmail以该人的电子邮件作为参数调用。

@Mock 
private EmailService emailService;

@InjectMocks
private Service service;

@Captor
private ArgumentCaptor<String> stringCaptor;

@Test
public void test_that_when_doSomething_is_called_sendEmail_is_called_NO_MOCKING() {

    final String email = "billy.tyne@myspace.com";

    // There is only one way of building an Address and it requires all these fields
    final Address crowsNest = new Address("334", "Main Street", "Gloucester", "MA", "01930", "USA");
    // There is only one way of building a Phone and it requires all these fields
    final Phone phone = new …
Run Code Online (Sandbox Code Playgroud)

java unit-testing mocking

5
推荐指数
1
解决办法
666
查看次数

标签 统计

unit-testing ×2

grails ×1

java ×1

mocking ×1