尝试创建一个仅在我的单元测试中调用一次的构造函数
public class ArtistTest extends InstrumentationTestCase{
private static final String TAG_NAME = "TESTING_SUITE";
private TestingMusicDAO musicDAO;
private List<Song> songs;
private Instrumentation instr;
MusicService musicService;
public ArtistTest() throws Exception {
super();
instr = this.getInstrumentation();
Log.d(TAG_NAME, "Setting up testing songs");
musicDAO = new TestingMusicDAO(instr.getContext());
musicService = new MusicServiceImpl(musicDAO);
musicDAO.getAllSongsFromFile();
songs = musicDAO.getAllSongs();
for(Song song : songs)
Log.d( TAG_NAME, song.toString() );
}
但是当我将文件作为Android Junit测试运行时,我在构造函数错误中遇到异常。这里还有堆栈跟踪
junit.framework.AssertionFailedError: Exception in constructor: test0 (java.lang.NullPointerException
at com.intellimec.ilane.ice.mediaservices.ArtistTest.<init>(ArtistTest.java:17)
at java.lang.reflect.Constructor.constructNative(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:417)
at junit.runner.BaseTestRunner.getTest(BaseTestRunner.java:118)
at android.test.AndroidTestRunner.getTest(AndroidTestRunner.java:148)
at android.test.AndroidTestRunner.setTestClassName(AndroidTestRunner.java:56)
at android.test.suitebuilder.TestSuiteBuilder.addTestClassByName(TestSuiteBuilder.java:80)
at android.test.InstrumentationTestRunner.parseTestClass(InstrumentationTestRunner.java:444)
at android.test.InstrumentationTestRunner.parseTestClasses(InstrumentationTestRunner.java:425)
at android.test.InstrumentationTestRunner.onCreate(InstrumentationTestRunner.java:370)
at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4382)
at android.app.ActivityThread.access$1300(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1294)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5039)
at java.lang.reflect.Method.invokeNative(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:190)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:175)
at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:555)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1661)
答案 0 :(得分:2)
将测试运行期间只需要执行一次的代码放入静态初始化程序中。加载类时应该只运行一次(不要重复使用这个类)。
答案 1 :(得分:0)
你也可以编写自己的setUp()方法来初始化你的“音乐”对象一次 有关详情,请参阅此页面 http://www.methodsandtools.com/tools/tools.php?junit
答案 2 :(得分:0)
ArtistTest.java:17
的内容是什么?
如果getInstrumentation
只返回private field instr
,那么它会在此处的调用中返回null,从而导致NPE更晚