プロダクトコード
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.メソッドへのアクセスを許可する。