Add CMake test target and fix Windows test failure

- Add TINYGLTF_BUILD_TESTS option to build unit tests via CMake
- Test runs from tests/ directory so relative paths work correctly
- Fix Windows file sharing violation in images-as-is test by closing
  fstream before stbi_load attempts to open the same file

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 4301fd1..ab2527a 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -14,6 +14,7 @@
 option(TINYGLTF_BUILD_GL_EXAMPLES "Build GL exampels(requires glfw, OpenGL, etc)" OFF)
 option(TINYGLTF_BUILD_VALIDATOR_EXAMPLE "Build validator exampe" OFF)
 option(TINYGLTF_BUILD_BUILDER_EXAMPLE "Build glTF builder example" OFF)
+option(TINYGLTF_BUILD_TESTS "Build unit tests" OFF)
 option(TINYGLTF_HEADER_ONLY "On: header-only mode. Off: create tinygltf library(No TINYGLTF_IMPLEMENTATION required in your project)" OFF)
 option(TINYGLTF_INSTALL "Install tinygltf files during install step. Usually set to OFF if you include tinygltf through add_subdirectory()" ON)
 option(TINYGLTF_INSTALL_VENDOR "Install vendored nlohmann/json and nothings/stb headers" ON)
@@ -37,6 +38,16 @@
   add_subdirectory ( examples/build-gltf )
 endif (TINYGLTF_BUILD_BUILDER_EXAMPLE)
 
+if (TINYGLTF_BUILD_TESTS)
+  enable_testing()
+  add_executable(tester tests/tester.cc)
+  target_include_directories(tester PRIVATE
+    ${CMAKE_CURRENT_SOURCE_DIR}
+    ${CMAKE_CURRENT_SOURCE_DIR}/tests
+  )
+  add_test(NAME tester COMMAND tester WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/tests)
+endif (TINYGLTF_BUILD_TESTS)
+
 #
 # for add_subdirectory and standalone build
 #
diff --git a/tests/tester.cc b/tests/tester.cc
index b06c30d..fe5981f 100644
--- a/tests/tester.cc
+++ b/tests/tester.cc
@@ -1121,8 +1121,10 @@
     // All the images should have been written to disk with their original data
     for (const auto& image : model.images)  {
       // Make sure the image files exist
-      std::fstream file(image.uri);
-      CHECK(file.good());
+      {
+        std::fstream file(image.uri);
+        CHECK(file.good());
+      } // Close file before stbi_load (Windows sharing violation fix)
 #ifndef TINYGLTF_NO_STB_IMAGE
       // Make sure we can load the images
       int w = -1, h = -1, component = -1;