首先在gredle文件中加入
defaultConfig { applicationId "com.example.app2" minSdkVersion 21 targetSdkVersion 23 versionCode 1 versionName "1.0" testInstrumentationRunner"android.support.test.runner.AndroidJUnitRunner" }
dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { exclude group: 'com.android.support', module: 'support-annotations' }) testCompile 'junit:junit:4.12' compile 'com.android.support:appcompat-v7:23.0.0' }
創建Java Class類 Array,編寫輸出數組中子數組最大值的和的代碼
public class Array { public int maxSum(int[] array) { if (array == null || array.length == 0) { throw new IllegalArgumentException("array is null or empty."); } int result = array[0], mark = 0; for (int i = 0; i < array.length; i++) { int element = array[i]; if (mark >= 0) { mark += element; } else { mark = element; } if (mark > result) { result = mark; } } return result; } }
創建測試類(選中Array右擊選擇Go to >Test),並編寫代碼
package com.example.app2; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; /** * Created by Tony on 2017/3/17. */ public class ArrayTest { private Array array; int sum []={1, -2, 3, 10, -4, 7, 2, -5}; @Before public void setUp() throws Exception { array =new Array(); } @Test public void testMaxSum() throws Exception { assertEquals(18d,array.maxSum(sum),0); } }
最后選中ArrayTest右擊選擇Run'ArrayTest',運行結果: