How do I run JUnit tests from a Windows CMD window

2019-04-17 02:53发布

问题:

Here is my JUnit test class: package com.bynarystudio.tests.storefront;

import java.util.List;

import org.junit.Assert;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;

import com.bynarystudio.tests.BaseWebTest;

public class SmokeTests extends BaseWebTest {

@Test
public void StoreFrontMegaNavTest(){
    webDriver.get(default_homepage);

    String source = webDriver.getPageSource();

    Assert.assertTrue(source.contains("some text"));    
}
}

How do I run this test from the command line? When I try to run it from inside its directory using

java -cp junit.textui.TestRunner SmokeTests.java

I get the following error

Could not find the main class: SmokeTests.java.  Program will exit.

I think this has to do with the fact that my classpath is not setup properly. But I have no idea because I'm brand new to Java. Coming from .NET, C#, and Visual Studio, the whole classpath thing makes no sense. Even though I have all my files correctly added to a project in Eclipse (I know because the test runs fine from inside Eclipse), it will absolutely not run or compile from the command line.

回答1:

First of all you are mixing two things:

  1. First you have to compile the project using javac command. As a result you will get set of .class files (not .java -> this is source code)

  2. Then you can run the code using java command: java -cp classPath yourpackage.SmokeTests

where:

classPath - is the list of directories or jar files where your compiled classes are, if you jave multiple entries separate them using ";" (windows) or ":"(Linux)

so your classPath can be: -cp .;c:/jars/*;deps

which means your classpath will contain:

  • current directory
  • all jar files from c:/jars/*
  • all jar files from deps directory that is in your working dir

So the full command can will be:

java -cp .;c:/jars/*;deps SmokeTests

yourpackage - is the package of the SmokeTests class, if you do not have package defined in the SmokeTests.java leave this empty