LoginSignup
1
1

More than 5 years have passed since last update.

privateメソッドをテストする時メモ

Posted at

プロダクトコード

GoodsCreateHelper.java
@Slf4j
@Service
@RequiredArgsConstructor
public class GoodsCreateHelper {

    private final GoodsService gService;

    private void create(final GoodsTbl entity) {
        gService.insert(entity);
    }
}

テストコード

GoodsCreateHelperTest.java
@ExtendWith(SpringExtension.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ActiveProfiles(profiles = {"test"})
@TestExecutionListeners({
        DependencyInjectionTestExecutionListener.class,
})
public class GoodsCreateHelperTest {

    @LocalServerPort
    private int port;

    @Autowired
    private GoodsCreateHelper create;

    @Nested
    @DisplayName("createTest")
    class createTest {

        @Test
        void createFail() throws Exception {
            Class<GoodsCreateHelper> clazz = GoodsCreateHelper.class;
            Method method = clazz.getDeclaredMethod("create", GoodsTbl.class);
            method.setAccessible(true);

            GoodsTbl entity = new GoodsTbl();
            InvocationTargetException e = Assertions.assertThrows(InvocationTargetException.class, () -> method.invoke(create, entity));
            Assertions.assertTrue(e.getCause().toString().contains("DataIntegrityViolationException"));
        }
    }
}

肝心なところ


Class<GoodsCreateHelper> clazz = GoodsCreateHelper.class;
Method method = clazz.getDeclaredMethod("create", GoodsTbl.class);
method.setAccessible(true);

GoodsTbl entity = new GoodsTbl();
InvocationTargetException e = Assertions.assertThrows(InvocationTargetException.class, () -> method.invoke(create, entity));

1.リフレクションでメソッド名をハードコーディングで指定している。
2.メソッドへのアクセスを許可する。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1