---
title: "MyEclipse中使用JUnit进行单元测试"
author: "beyondbn"
date: "2015-03-17T10:42:13Z"
tags: []
categories: ["非技术"]
slug: "myeclipse-junit"
draft: false
lastmod: "2015-03-17T10:42:13Z"
id: 2193054
url: "https://beyondbn.iteye.com/blog/2193054"
---

**参考：http://yukaizhao.iteye.com/blog/1541768**

 

1\. 下载JUnit的jar文件，下载地址在[这里](https://github.com/KentBeck/junit/downloads)

2\. 在MyEclipse中新建一个要测试的项目HelloJUnit

3\. 添加一个要测试的类HelloJUnit，代码如下，注意需要先建package

 

Java代码  [![收藏代码](http://yukaizhao.iteye.com/images/icon_star.png)]()

1. package com.yukaizhao;
2. public class HelloJUnit {
3. public String getMessage(){
4. return "Hello Junit";
5. }
6. }

4\. 新建一个单元测试项目，命名为HelloJUnitTest，引用在第一步中下载的jar文件，如下下图所示

![add junit](http://dl.iteye.com/upload/picture/pic/113057/432d1aea-ea01-3fc9-b2da-b864eee33da8.png "点击查看原始大小图片")

5\. 添加测试类，HelloJUnitTest，需要提前建package

 

Java代码  [![收藏代码](http://yukaizhao.iteye.com/images/icon_star.png)]()

01. package com.yukaizhao;
02. /\*引用测试相关类和方法\*/
03. import org.junit.Test;
04. import org.junit.Before;
05. import static org.junit.Assert.\*;
06. public class HelloJUnitTest {
07. private HelloJUnit \_target;
08. @Before
09. public void beforeTest(){
10. \_target = new HelloJUnit();
11. }
12. @Test
13. public void testGetMessage(){
14. String expected = "Hello Junit";
15. String actual = \_target.getMessage();
16. assertEquals(expected,actual);
17. }
18. }

 6. 运行测试，在项目上单击右键，然后选择Run as --&gt; JUnit Test

![](http://dl.iteye.com/upload/picture/pic/113061/9ae06b43-5c24-3adb-8c3c-7518437083e2.png)