1

私はいくつかの grails コントローラーを生成し、わずかに変更しました。私は生成された単体テストを処理して合格させていますが、難しい方法でやっていると思います。これは私が持っているものです。

package edu.liberty.swiper

import grails.test.mixin.*

import org.junit.*

@TestFor(AttendanceController)
@Mock([Attendance, Location, Reason, Person, LocCapMode, GuestContactMode, UserAccount])
class AttendanceControllerTests {

def location
def reason

void setUp() {
    def capMode = new LocCapMode(description: "loc cap mode", username: "testuser").save(failOnError: true)
    def guestMode = new GuestContactMode(description: "Guest Contact Mode", username: "testuser").save(failOnError: true)
    location = new Location(description: "foo", locCapMode: capMode, username: "testuser", guestContactMode: guestMode).save(failOnError: true)
    reason = new Reason(description: "test reason", username: "testuser").save(failOnError: true)
    def person = new Person(firstName: "John", lastName: "Smith", lid: "L12345678", mi: "Q", pidm: 12345).save(failOnError: true)
    def userAccount = new UserAccount(pidm: 12345, username: "testuser").save(failOnError:true)
}

def populateValidParams(params) {
    assert params != null
    params.personId = '12345'
    params.username = "testuser"
    params["location.id"] = location.id
    params["reason.id"] = reason.id
    params.timeIn = new Date()
}

void testIndex() {
    ...
}

void testList() {
    ...
}

void testCreate() {
    ...
}

void testSave() {
    controller.save()

    assert model.attendanceInstance != null
    assert view == '/attendance/create'

    response.reset()

    populateValidParams(params)
    controller.save()

    assert response.redirectedUrl == '/attendance/show/1'
    assert controller.flash.message != null
    assert Attendance.count() == 1
}

void testEdit() {
    ...
}

...

私が望んでいるのは、ドメインオブジェクト、つまりexpect(Attendance.save()).andReturn(null)orを動的にモックする機能ですexpect(Attendance.save()).andReturn(testAttendance)。これにより、 setUp メソッドで関連オブジェクトのウェブを作成する必要がなくなりますコントローラ。

私はこれをすべて間違って見ているだけですか?コントローラーロジックを検証ロジックから切り離すことができるように思われるので、検証が成功したか失敗したかをコントローラーに伝えるようにモックに指示できます。前もって感謝します。

4

2 に答える 2

1

単体テストのモックを作成する場合、単一のドメインをテストするために必要なすべての値を含む完全なオブジェクト グラフを用意する必要はありません。たとえば、このようなものを持つことができます..

def department = new Department(name: "Accounting").save(validate: false)
def user = new User(username: "gdboling", department: department).save()

ユーザーに必要なフィールドがユーザー名と部門の 2 つだけであると仮定しますが、部門には検証に失敗する他の多くのフィールドがある可能性があります。これは、本当にテストする必要があるのがユーザーだけである場合でも機能します。

でそれらを指定する必要がありますが@Mock、すべての血なまぐさいフィールドにデータを入力する必要はありません。:)

于 2013-10-22T22:20:41.710 に答える