|
|
基于你提供的 VoskHelper 类,以下是使用准备好的 WAV 文件进行测试的例子:
1. 单元测试示例
- public class VoskHelperTest {
- private Context context;
-
- @Before
- public void setUp() {
- context = InstrumentationRegistry.getInstrumentation().getContext();
- }
-
- @Test
- public void testSendFileWithWav() {
- // 首先将assets中的wav文件复制到可访问位置
- copyWavFileFromAssets();
-
- // 修改MyAudioRecord.filePath指向测试文件
- MyAudioRecord.filePath = "/data/data/your.package.name/test_audio.wav";
-
- // 调用VoskHelper.sendFile()
- VoskHelper.sendFile();
-
- // 这里可以添加验证逻辑,比如检查是否成功连接等
- assertNotNull("WebSocket should be created", getClient());
- }
-
- private void copyWavFileFromAssets() {
- try {
- AssetManager assetManager = context.getAssets();
- InputStream inputStream = assetManager.open("test_audio.wav");
-
- File outputFile = new File(context.getFilesDir(), "test_audio.wav");
- FileOutputStream outputStream = new FileOutputStream(outputFile);
-
- byte[] buffer = new byte[1024];
- int length;
- while ((length = inputStream.read(buffer)) > 0) {
- outputStream.write(buffer, 0, length);
- }
-
- inputStream.close();
- outputStream.close();
-
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
复制代码
2. 集成测试示例
- @RunWith(AndroidJUnit4.class)
- public class VoskHelperIntegrationTest {
-
- @Test
- public void testWebSocketConnectionAndFileTransfer() {
- // 设置测试文件路径
- MyAudioRecord.filePath = getTestWavFilePath();
-
- // 执行文件发送
- VoskHelper.sendFile();
-
- // 等待一段时间让WebSocket连接和文件传输完成
- try {
- Thread.sleep(5000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
-
- // 验证结果(可以通过Mock WebSocket或者检查日志)
- assertTrue("File should be sent successfully", true);
- }
-
- private String getTestWavFilePath() {
- // 返回测试WAV文件的路径
- return "/android_asset/test_audio.wav"; // 如果放在assets目录
- // 或者返回实际文件系统的路径
- }
- }
复制代码
3. 使用Mock进行测试
- @Test
- public void testHandleEofReceipt() {
- // 直接测试VoskHelper的受保护方法
- String testReceipt = "{"result":[],"text":""}";
-
- // 由于handleEofReceipt是protected static方法,可以通过反射调用
- try {
- Method method = VoskHelper.class.getDeclaredMethod("handleEofReceipt", String.class);
- method.setAccessible(true);
- method.invoke(null, testReceipt);
-
- // 验证日志输出或者其他副作用
- assertTrue("Method should execute without exception", true);
- } catch (Exception e) {
- fail("Should not throw exception: " + e.getMessage());
- }
- }
复制代码
4. 注意事项
1) 文件路径: 确保 MyAudioRecord.filePath 指向正确的测试WAV文件路径
2) 网络连接: 测试时需要确保能够连接到指定的WebSocket服务器 (ws://10.10.5.56:2700)
3) 权限: 如果在Android设备上运行,确保有读取文件的权限
4) 异步处理: VoskHelper.sendFile() 是异步操作,测试时需要适当等待
这些测试例子可以帮助你验证 VoskHelper 类的功能是否正常工作。
|
|