断言 - 内部调用的问题



大家好,我在第一次测试时遇到了一些问题

我正在写这个片段,但我总是遇到这个问题:

java.lang.AssertionError at org.junit.Assert.fail(Assert.java:86( at org.junit.Assert.assertTrue(Assert.java:41( at org.junit.Assert.assertNotNull(Assert.java:712( at org.junit.Assert.assertNotNull(Assert.java:722(

有人知道热来帮助我吗? 也许还有哪些是在这个课程中测试的正确内容? 非常感谢

我已经在 gradle 中实现了 Junit

测试类是:

public class QrActivityTest {
public QrActivity tester;
@Before
public void setUp(){
tester = new QrActivity();
}
@Test
public void onCreate() {
//barcodeDetector = new BarcodeDetector.Builder(tester.getApplicationContext()).setBarcodeFormats(Barcode.QR_CODE).build();
// Assert.assertNotNull(barcodeDetector);
Assert.assertNotNull(tester);
Assert.assertNotNull(tester.cameraSource);
}}

该类是:

public class QrActivity extends AppCompatActivity {
SurfaceView surfaceView;
CameraSource cameraSource;
TextView textView;
BarcodeDetector barcodeDetector;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.barcode_scanner_layout);
surfaceView = (SurfaceView) findViewById(R.id.camera);
textView = (TextView) findViewById(R.id.txt);
barcodeDetector = new BarcodeDetector.Builder(this).setBarcodeFormats(Barcode.QR_CODE).build();
cameraSource = new CameraSource.Builder(this, barcodeDetector).setRequestedPreviewSize(640, 480).setAutoFocusEnabled(true).build();
surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
@Override
public void surfaceCreated(SurfaceHolder holder) {
if (ActivityCompat.checkSelfPermission(QrActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
return;
}
try {
cameraSource.start(holder);
} catch (IOException e) {
Toast.makeText(QrActivity.this, "errore fotoamera", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}

//this is to take data

@Override
public void receiveDetections(Detector.Detections<Barcode> detections) {
final SparseArray<Barcode> qrCodes = detections.getDetectedItems();
if (qrCodes.size() != 0) {
textView.post(new Runnable() {
@Override
public void run() {
Vibrator vibrator = (Vibrator) getApplicationContext().getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(300);
textView.setText(qrCodes.valueAt(0).displayValue);
if (qrCodes.valueAt(0).displayValue.equals("129063")) {
Intent intent = new Intent(QrActivity.this, AttrezzaturaRecycleView.class);
startActivity(intent);
Utility.showToast(QrActivity.this, "Dispositivo trovato!");
}
}
});
}

断言检查内部值。如果未满足断言,则会引发异常。因此,您可以检查完整的堆栈跟踪。

异常可能发生在行Assert.assertNotNull(tester.cameraSource);中。这是因为相机源将为空。这是因为您只创建了类的实例,但没有调用onCreate等事件。简单的单元测试不足以进行前端测试。

您可能需要一个检测的测试用例。请求尝试使用 JUnit 测试规则来实例化活动。需要设备或模拟器才能运行此测试。

@finder2 sais,问题是,tester.cameraSourcenull

我认为,这是因为方法onCreate()从未执行过。

您可以像往常一样启动应用程序,也可以使用反射运行onCreate

您还可以在构造函数或公共方法中移动必要的代码。

最新更新