Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

util: write tests for endpoints #4

Open
Scharxi opened this issue May 18, 2023 · 0 comments
Open

util: write tests for endpoints #4

Scharxi opened this issue May 18, 2023 · 0 comments

Comments

@Scharxi
Copy link
Owner

Scharxi commented May 18, 2023

Write some tests to check if the endpoints do what they have to do

e.g.

package main_test

import (
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/golang/mock/gomock"
	"github.com/stretchr/testify/assert"

	"yourpackage/dataservice"
	"yourpackage/restapi"
	"yourpackage/restapi/mocks"
)

func TestGetUser(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()

	// Mock-Implementierung der Datenzugriffsschicht
	mockDataService := mocks.NewMockDataService(ctrl)
	mockDataService.EXPECT().GetUser(1).Return(&dataservice.User{ID: 1, Name: "John"}, nil)

	// REST-API-Handler initialisieren und den DataService setzen
	apiHandler := restapi.NewAPIHandler()
	apiHandler.SetDataService(mockDataService)

	// HTTP-Request und -Response simulieren
	req, _ := http.NewRequest("GET", "/users/1", nil)
	rec := httptest.NewRecorder()

	// Handler aufrufen
	apiHandler.ServeHTTP(rec, req)

	// Überprüfen der HTTP-Response
	assert.Equal(t, http.StatusOK, rec.Code)
	assert.Equal(t, `{"id":1,"name":"John"}`, rec.Body.String())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant