본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

유닛 테스트 (Unit Testing)

원문 보기 위키 갱신

PHP SDK에서 유닛 및 통합 테스트는 일급 시민(first-class citizens)이에요. DI 컨테이너, 목(mocks), 스텁(stubs), 그리고 제공되는 \Dapr\Mocks\TestClient를 사용하면 매우 세밀한 테스트를 작성할 수 있어요.

출처: Dapr 문서

본문

액터 테스트하기 (Testing Actors)

액터의 경우, 액터를 테스트하는 동안 관심을 가질 두 가지가 있어요:

  • 초기 상태를 기반으로 한 반환 결과

  • 초기 상태를 기반으로 한 결과 상태

  • TestClient를 사용한 통합 테스트 (integration test with TestClient)

  • 유닛 테스트 (unit test)

다음은 상태를 업데이트하고 특정 값을 반환하는 매우 단순한 액터의 테스트 예시예요:

<?php

// TestState.php

class TestState extends \Dapr\Actors\ActorState
{
public int $number;
}

// TestActor.php

#[\Dapr\Actors\Attributes\DaprType('TestActor')]
class TestActor extends \Dapr\Actors\Actor
{
public function __construct(string $id, private TestState $state)
{
parent::__construct($id);
}

public function oddIncrement(): bool
{
if ($this->state->number % 2 === 0) {
return false;
}
$this->state->number += 1;

return true;
}
}

// TheTest.php

class TheTest extends \PHPUnit\Framework\TestCase
{
private \DI\Container $container;

public function setUp(): void
{
parent::setUp();
// create a default app and extract the DI container from it
$app = \Dapr\App::create(
configure: fn(\DI\ContainerBuilder $builder) => $builder->addDefinitions(
['dapr.actors' => [TestActor::class]],
[\Dapr\DaprClient::class => \DI\autowire(\Dapr\Mocks\TestClient::class)]
));
$app->run(fn(\DI\Container $container) => $this->container = $container);
}

public function testIncrementsWhenOdd()
{
$id = uniqid();
$runtime = $this->container->get(\Dapr\Actors\ActorRuntime::class);
$client = $this->getClient();

// return the current state from http://localhost:1313/reference/api/actors_api/
$client->register_get("/actors/TestActor/$id/state/number", code: 200, data: 3);

// ensure it increments from http://localhost:1313/reference/api/actors_api/
$client->register_post(
"/actors/TestActor/$id/state",
code: 204,
response_data: null,
expected_request: [
[
'operation' => 'upsert',
'request' => [
'key' => 'number',
'value' => 4,
],
],
]
);

$result = $runtime->resolve_actor(
'TestActor',
$id,
fn($actor) => $runtime->do_method($actor, 'oddIncrement', null)
);
$this->assertTrue($result);
}

private function getClient(): \Dapr\Mocks\TestClient
{
return $this->container->get(\Dapr\DaprClient::class);
}
}
<?php

// TestState.php

class TestState extends \Dapr\Actors\ActorState
{
public int $number;
}

// TestActor.php

#[\Dapr\Actors\Attributes\DaprType('TestActor')]
class TestActor extends \Dapr\Actors\Actor
{
public function __construct(string $id, private TestState $state)
{
parent::__construct($id);
}

public function oddIncrement(): bool
{
if ($this->state->number % 2 === 0) {
return false;
}
$this->state->number += 1;

return true;
}
}

// TheTest.php

class TheTest extends \PHPUnit\Framework\TestCase
{
public function testNotIncrementsWhenEven() {
$container = new \DI\Container();
$state = new TestState($container, $container);
$state->number = 4;
$id = uniqid();
$actor = new TestActor($id, $state);
$this->assertFalse($actor->oddIncrement());
$this->assertSame(4, $state->number);
}
}

트랜잭션 테스트하기 (Testing Transactions)

트랜잭션을 기반으로 구축할 때, 실패한 트랜잭션이 어떻게 처리되는지 테스트하고 싶을 거예요. 그러려면 실패를 주입하고 트랜잭션이 기대한 것과 일치하는지 확인해야 해요.

  • TestClient를 사용한 통합 테스트 (integration test with TestClient)
  • 유닛 테스트 (unit test)
<?php

// MyState.php
#[\Dapr\State\Attributes\StateStore('statestore', \Dapr\consistency\EventualFirstWrite::class)]
class MyState extends \Dapr\State\TransactionalState {
public string $value = '';
}

// SomeService.php
class SomeService {
public function __construct(private MyState $state) {}

public function doWork() {
$this->state->begin();
$this->state->value = "hello world";
$this->state->commit();
}
}

// TheTest.php
class TheTest extends \PHPUnit\Framework\TestCase {
private \DI\Container $container;

public function setUp(): void
{
parent::setUp();
$app = \Dapr\App::create(configure: fn(\DI\ContainerBuilder $builder)
=> $builder->addDefinitions([\Dapr\DaprClient::class => \DI\autowire(\Dapr\Mocks\TestClient::class)]));
$this->container = $app->run(fn(\DI\Container $container) => $container);
}

private function getClient(): \Dapr\Mocks\TestClient {
return $this->container->get(\Dapr\DaprClient::class);
}

public function testTransactionFailure() {
$client = $this->getClient();

// create a response from https://docs.dapr.io/reference/api/state_api/
$client->register_post('/state/statestore/bulk', code: 200, response_data: [
[
'key' => 'value',
// no previous value
],
], expected_request: [
'keys' => ['value'],
'parallelism' => 10
]);
$client->register_post('/state/statestore/transaction',
code: 200,
response_data: null,
expected_request: [
'operations' => [
[
'operation' => 'upsert',
'request' => [
'key' => 'value',
'value' => 'hello world'
]
]
]
]
);
$state = new MyState($this->container, $this->container);
$service = new SomeService($state);
$service->doWork();
$this->assertSame('hello world', $state->value);
}
}
<?php
// MyState.php
#[\Dapr\State\Attributes\StateStore('statestore', \Dapr\consistency\EventualFirstWrite::class)]
class MyState extends \Dapr\State\TransactionalState {
public string $value = '';
}

// SomeService.php
class SomeService {
public function __construct(private MyState $state) {}

public function doWork() {
$this->state->begin();
$this->state->value = "hello world";
$this->state->commit();
}
}

// TheTest.php
class TheTest extends \PHPUnit\Framework\TestCase {
public function testTransactionFailure() {
$state = $this->createStub(MyState::class);
$service = new SomeService($state);
$service->doWork();
$this->assertSame('hello world', $state->value);
}
}

더 알아보기 (Learn more)