我的java项目有Controller(依赖)Service(依赖)DAO等多层。我的目标是对控制器进行单元测试。
我创建了 Mock 服务对象以将其注入到 Controller 类中。
谷歌搜索后,我了解到我可以使用 java 接口来做到这一点。
理想情况下,服务层不需要接口。
我想知道是否有不同的方法可以在没有 java 接口的情况下注入模拟对象。
我在运行Junit脚本时遇到一个问题.我收到以下错误消息.
我有三个java类,我在其中评论了来自A类和B类的所有@Test注释,但在C类中有4个@Test注释.但它仍然显示以下错误消息.
任何人都可以帮我解决这个问题吗?
Error: java.lang.Exception: No runnable methods
at org.junit.runners.BlockJUnit4ClassRunner.validateInstanceMethods(BlockJUnit4ClassRunner.java:169)
at org.junit.runners.BlockJUnit4ClassRunner.collectInitializationErrors(BlockJUnit4ClassRunner.java:104)
at org.junit.runners.ParentRunner.validate(ParentRunner.java:355)
at org.junit.runners.ParentRunner.<init>(ParentRunner.java:76)
at org.junit.runners.BlockJUnit4ClassRunner.<init>(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.Parameterized$TestClassRunnerForParameters.<init>(Parameterized.java:171)
at org.junit.runners.Parameterized.createRunnersForParameters(Parameterized.java:319)
at org.junit.runners.Parameterized.<init>(Parameterized.java:282)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
Run Code Online (Sandbox Code Playgroud)
有人可以帮忙吗?
我从 Eclipse 执行 spring 3.2.8 项目的这个 Junit (junit-4.4) 没有问题,(单击右键 -> Run As -> Junit Test)
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
public class AccomodationTypeDaoTest extends BaseDaoTest {
private AccomodationTypeDao accTypeDao;
@Test
public void testFindAll() {
assertNotNull(accTypeDao.findAll());
}
@Autowired
public void setAccomodationTypeDao(AccomodationTypeDao daoInstance) {
this.accTypeDao = daoInstance;
}
}
@SuppressWarnings("deprecation")
public class BaseDaoTest extends AbstractAnnotationAwareTransactionalTests {
private static final String[] CONFIG_LOCATIONS = new String[] { "classpath:com/dao/testDataAccessContext.xml" };
@Override
protected String[] getConfigLocations() {
return CONFIG_LOCATIONS;
}
@Test
public void testBaseDaoTest() {
assertTrue(true);
}
} …Run Code Online (Sandbox Code Playgroud) 如何使用JUnit 4指定人类可读的测试名称(在IDE和测试报告中显示)?
理想情况下,通过自动转换实际的测试名称。
我在一个项目中工作,其中包含许多嵌入了errorCode的"BusinessException".
在每个单元测试异常中,我必须测试这些错误代码重复这种模式:
@Test
public void zipFileReaderCtorShouldThrowAnExceptionWithInexistingArchive() {
try {
zfr = new ZipFileReader("unexpected/path/to/file");
fail("'BusinessZipException' not throwed");
} catch (BusinessZipException e) {
assertThat("Unexpected error code", e.getErrorCode(), is(ErrorCode.FILE_NOT_FOUND));
} catch (Exception e) {
fail("Unexpected Exception: '" + e + "', expected: 'BusinessZipException'");
}
}
Run Code Online (Sandbox Code Playgroud)
(由于错误代码测试,使用JUnit注释是不可能的)
我很无聊,特别是因为我必须在fail()的错误消息中复制/粘贴异常名称.
所以,我写了一个Util类.我使用抽象类来处理异常断言测试.
public abstract class TestExceptionUtil {
public void runAndExpectException(Class expectedException, String expectedErrorCode) {
String failUnexpectedExceptionMessage = "Unexpected exception. Expected is: '%s', but got: '%s'";
try {
codeToExecute();
fail("'" + expectedException.getName() + "' not throwed");
} catch … 我正在使用 JDK 1.7、eclipse 4.2.2、JUnit 4.8.1、ant 1.9.2、windows8 64 位**当我运行 build.xml 时,所有目标都运行良好,但名称为run的目标运行不正常.
<?xml version="1.0" encoding="UTF-8"?>
<project name="AntExample" default="setclasspath" basedir=".">
<!-- Properties Initialization -->
<property environment="env"/>
<property name="ws.home" value="${basedir}" />
<property name="ws.jar" value="${basedir}/lib" />
<property name="test.dest" value="${basedir}/build" />
<property name="test.src" value="${basedir}/src" />
<property name="test.reportsDir" value="E:\Reports" />
<!-- Path Initialization -->
<path id="testcase.path">
<pathelement location="${ws.jar}"/>
<pathelement path="${classes}"/>
<fileset dir="${ws.jar}">
<include name="**/*.jar"/>
</fileset>
</path>
<!-- Target Setclasspath -->
<target name="setclasspath" unless="testcase.path">
<path id="classpath_jars">
<fileset dir="${ws.jar}">
<include name="**/*.jar"/>
</fileset>
</path>
<pathconvert …Run Code Online (Sandbox Code Playgroud) 嗨,我想使用基本测试,一些测试将会提供.这是我的基地
@RunWith(MockitoJUnitRunner.class)
public class BaseOmsUnitTest {
@BeforeClass
public static void setUpBeforCalss() throws Throwable{
JunitUtils.mockIlSession();
OMSDomainsMocker helper = new OMSDomainsMocker();
helper.mockOMSDomainConnection();
}
@Test
public void dummyTest(){
}
}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,我希望每个继承此基本测试的类都具有相同的init我还故意添加@RunWith注释作为init需要此运行器.但是当我用maven运行测试而没有放置一个dummyTest它给了我
没有在Base找到的测试你有没有忘记@Test注释?
我可以在不使用这个dummyTest的情况下克服这一点
我是 JUnit 新手,正在尝试学习。我们如何为 void 方法编写 JUnit?我有一个无效的删除方法。我正在编写如下测试,但它不起作用。请建议。
我必须为其编写测试用例的方法。
public class DoseService {
@Autowired
private DoseRepository doseRepo;
public void deleteDose(int id) {
doseRepo.deleteById(id);
}
}
Run Code Online (Sandbox Code Playgroud)
我的测试
@Autowired
private DoseService doseService;
@MockBean
public DoseRepository doseRepository;
@Test
public void testDeleteDose() {
Dose dose = createDose();
ArgumentCaptor<Dose> arg = ArgumentCaptor.forClass(Dose.class);
doseService.deleteDose(dose.getDoseId());
verify(doseRepository).deleteById(arg.capture().getDoseId());
assertEquals("120", arg.getValue().getDoseValue());
}
private Dose createDose() {
Dose dose = new Dose();
dose.setDoseId(1);
dose.setDoseValue("120");
return dose;
}
Run Code Online (Sandbox Code Playgroud)
提前致谢
更新
java.lang.NullPointerException
at verify(doseRepository).deleteById(arg.capture().getDoseId());
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at
java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50) …Run Code Online (Sandbox Code Playgroud) 我的目标很少,我需要执行.我创建了一个目标,命名所有这些,但我认为这不是这样做的方法吗?以下是调用所有其他目标的目标运行:
<target name="test.all" depends="build
echolaunching agent /echo
antcall target="RunJtfTests" /
antcall target="launchOpenAgent" /
antcall target="run.test" //target
target name="run.test" depends="build, launchOpenAgent, runJtfTests"
echo Launching test/echo
echo message="${toString:iControlSilk4J.classpath}" /
<java classname="com.miranda.icontrol.silk4j.installation.AdministrationCtrl"
classpath><fileset dir="${lib.dir}"
include name="**/*.jar" />
/fileset
pathelement path="${iControlSilk4J.classpath}" /
pathelement location="${jarPath}/Admin.jar" /
/classpath
</java>
</target>
Run Code Online (Sandbox Code Playgroud)
它没有运行,我这样做是为了得到报告而我什么都没得到?怎么了 ?从我读到的,antcall就像一个不好的goto循环.我想打电话给测试.
- >以下是我想要执行的所有测试:
但这可能更通用(关于我将在Silk4J中添加的测试).有没有办法更通用?
我使用了JUnit 3,当我编写这段代码时,我收到了这个错误
AssertionFailedError:未找到测试
import junit.framework.TestCase;
import junit.runner.*;
public class Teststd extends TestCase {
Student s;
public void setUp() {
s = new Student("ASJFA");
}
public void TestEmail() {
try {
s.setEmail("KUKU");
assertTrue(false);
} catch (EmailIsInvalid ex) {
assertTrue(true);
System.out.println("Exception caught. Email is invalid");
}
}
public void tearDown() {
}
}
Run Code Online (Sandbox Code Playgroud) 在Java应用程序中,我有一个类的方法,只使用其名称保存文件.
public void doSomething(){
final File file = new File("XXX"+(new Random().next())+".txt");
file.createNewFile();
}
Run Code Online (Sandbox Code Playgroud)
然后,在使用JUnit 4的单元测试中,我运行执行该方法的类,并XXX.txt在项目的根文件夹中看到使用name创建的文件.
@Test
public void doSomethingTest() throws Exception{
//call doSomething();
Path path = //to project folder
Files.delete(path);
}
Run Code Online (Sandbox Code Playgroud)
如何动态获取此路径,以便我可以使用@After方法删除它?