Skip to content

Commit

Permalink
ApiExceptionが発生しそれをcatchできたことがログから確認できるようなテストを作成
Browse files Browse the repository at this point in the history
  • Loading branch information
ShioriPeace committed Aug 16, 2024
1 parent 5bd93d1 commit 01afa53
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 22 deletions.
2 changes: 1 addition & 1 deletion src/shortcodes/product/class-page.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ public static function show( $container, $atts, $content, $tag ) {
$product = $container['api.product_api']->fetch( $filtered_atts['product_id'] )['product'];
} catch ( \ColorMeShop\Swagger\ApiException $e ) {
if ( $container['WP_DEBUG_LOG'] ) {
error_log( $e );
error_log( '存在しない商品IDが指定された可能性があります。' . $e );
}
return '';
} catch ( \RuntimeException $e ) {
Expand Down
66 changes: 45 additions & 21 deletions tests/src/shortcodes/product/class-page-test.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,34 @@
namespace ColorMeShop\Shortcodes\Product;

class Page_Test extends \WP_UnitTestCase {

/** @var \Pimple\Container */
private $container;

/** @var string */
private $error_log;

/** @var string */
private $original_error_log;

public function setUp() {
parent::setUp();

$this->container = _get_container();
$this->container['token'] = function ( $c ) {
return 'dummy';
};

// ログ出力先
$this->error_log = tempnam( sys_get_temp_dir(), 'TEST' );
$this->original_error_log = ini_set( 'error_log', $this->error_log );
}

public function tearDown() {
parent::tearDown();
ini_set( 'error_log', $this->original_error_log );
}

/**
* @test
*/
Expand Down Expand Up @@ -29,30 +57,26 @@ public function show_テンプレート名が不正な場合は空文字を返
/**
* @test
*/
public function show_存在しない商品IDが指定された場合は、ApiExceptioncatchし空文字を返す() {
$container = $this->createMock(\Pimple\Container::class);
$product_api = $this->createMock(\ColorMeShop\Swagger\Api\ProductApi::class);

$product_api->method('fetch')
->willThrowException(new \ColorMeShop\Swagger\ApiException());

$container->method('offsetGet')
->willReturnMap([
['api.product_api', $product_api],
['WP_DEBUG_LOG', false],
]);
public function show_存在しない商品IDが指定された場合、デバッグが有効であればエラーメッセージを出力し、空文字を返す() {
$this->container['WP_DEBUG_LOG'] = function ( $c ) {
return true;
};

$pageShow = Page::show(
$this->container,
[
'template' => 'default',
'product_id' => '00000000',
],
null,
null
);

$this->assertSame(
'',
Page::show(
$container,
[
'template' => 'default',
'product_id' => '999999', // 存在しない商品ID
],
null,
null
)
$pageShow
);

$this->assertStringContainsString( '存在しない商品IDが指定された可能性があります。', file_get_contents( $this->error_log ) );
}
}

0 comments on commit 01afa53

Please sign in to comment.