标签: junit4

Junit:我如何使用断言来检查 String >0

我有一个字符串,我想使用 assert 检查这个字符串是否 > 0

尝试:使用 assertFalse 我无法设置 2 个字符串:我的值和 "0" 。

还有另一种说法: assertThat "myString"> "0" 吗?

我的目的 :

myTable.getValue =>this return a string : "20"
I would like to check that this string is > or different from "0" 
Run Code Online (Sandbox Code Playgroud)

谢谢

junit4

2
推荐指数
1
解决办法
4176
查看次数

JUnit4:测试预期的异常

我试图用JUnit4测试抛出异常的方法.这是代码片段:

package unit_tests;

import org.junit.Test;
import calculator.*;

@Test(expected=CalcError.class)
public void testDivision() {
    Calculator myCalc = new Calculator(10, 0);
    myCalc.setOperation(Calculator.Operation_e.DIVIDE);
    myCalc.getResult();
}
Run Code Online (Sandbox Code Playgroud)

问题在于@Test(expected=CalcError.class):我收到以下错误:

Class<CalcError> cannot be resolved to a type
Run Code Online (Sandbox Code Playgroud)

以下是如何CalcError定义:

package calculator;

public class Calculator {
    public class CalcError extends Exception {
        // ...
    }

    public double getResult() throws CalcError {
        // ...
    }
}
Run Code Online (Sandbox Code Playgroud)

我不明白为什么CalcError不是一个类型,即使单元测试在一个unit_tests包中并且计算器在一个calculator包中.

我错过了什么?

java junit junit4

2
推荐指数
1
解决办法
2358
查看次数

将 JdbcTemplate 更新方法与 Mockito 匹配

我正在尝试匹配我在 Dao 类中使用的这种方法。但我总是收到以下异常,表明未在该方法上进行调用。

要么方法不匹配,要么我做错了什么。

String pSql = "SELECT * FROM employee";
Object[] pArgs = new Object[] {""};
int[] pArgTypes =  new int[] {};

/* Return 1 when the call to update() is made indicating a successful database update */
when(mJdbcTemplate.update(anyString(), aryEq(pArgs), aryEq(pArgTypes))).thenReturn(1);
Run Code Online (Sandbox Code Playgroud)

这是异常的堆栈跟踪:

Wanted but not invoked:
jdbcTemplate.update(<any>, <any>, <any>);
-> at com.test.GenericDaoJdbcImplTest$WhenInsertUpdateDeleteIsCalledWith.successfulUpdateShouldReturnTrue(GenericDaoJdbcImplTest.java:197)

However, there were other interactions with this mock:
-> at com.test.GenericDaoJdbcImplTest.insertUpdateDelete(GenericDaoJdbcImpl.java:121)

    at org.mockito.exceptions.Reporter.wantedButNotInvoked(Reporter.java:269)
    at org.mockito.internal.verification.checkers.MissingInvocationChecker.check(MissingInvocationChecker.java:42)
    at org.mockito.internal.verification.Times.verify(Times.java:36)
    at org.mockito.internal.verification.MockAwareVerificationMode.verify(MockAwareVerificationMode.java:21)
    at org.mockito.internal.MockHandler.handle(MockHandler.java:80)
    at org.mockito.internal.InvocationNotifierHandler.handle(InvocationNotifierHandler.java:36)
    at org.mockito.internal.creation.MethodInterceptorFilter.intercept(MethodInterceptorFilter.java:48)
    at org.springframework.jdbc.core.JdbcTemplate$$EnhancerByMockitoWithCGLIB$$92326890.update(<generated>) …
Run Code Online (Sandbox Code Playgroud)

java junit junit4 mockito

2
推荐指数
1
解决办法
8359
查看次数

如何在命令行触发的junit测试中添加参数?

这个线程在这里展示了如何使用JUnit测试来测试JAR.但是,我想从命令行提交其他属性(因为我想测试我的main方法).

如何从命令行运行Java的JUnit测试

例如java -cp /usr/share/java/junit.jar org.junit.runner.JUnitCore [MyTest] [PortNumber] [fileToRead]

有可能吗?

java junit4

2
推荐指数
1
解决办法
5527
查看次数

测试JUnit中方法的合法和非法参数

如果我想测试输入是否有效,我如何使用JUnit4来测试该方法是否处理非法输入/参数?

要调用setAge()方法,参数必须是整数而不是char或string.

@Test
public void testWHetherInputValid() {
    Person p = new Person();
    String s = "abc";
    p.setAge(s); // but actually, the correct input must be an integer
}
Run Code Online (Sandbox Code Playgroud)

java junit junit4

2
推荐指数
1
解决办法
1637
查看次数

为什么在将泛型方法args转换为特定方法时无法转换为类型?

我为科学计算器编写了一个java代码,并为它编写了jUnit测试.Below是计算cubeRoot的方法.

public <T> Double cubeRoot(T number){
    Double result= Math.cbrt((Double)number);
    return Math.abs(result);
}
Run Code Online (Sandbox Code Playgroud)

方法返回正确的结果整数和double类型,但是当我调用十进制方法时,参数i pass是double类型.以下是上述方法的JUint Test.

public void testCalculateCubeRootWhenNegative(){
    Integer number=-64;
    assertEquals(-4.0,sci.cubeRoot(number));
}

public void testCalculateCubeRootOfdecimal(){
    Double number=0.40;
    assertEquals(0.736,sci.cubeRoot(number));
}
Run Code Online (Sandbox Code Playgroud)

这就是我正在使用的界面

public interface iScientific extends iMaths {
<T>Double squareRoot(T number);

<T>Double cubeRoot(T number);
Run Code Online (Sandbox Code Playgroud)

无法找到获取错误的解决方案"java.lang.ClassCastException:java.lang.Integer无法强制转换为java.lang.Double"

java junit4

2
推荐指数
1
解决办法
75
查看次数

Mockito和回调返回“参数不同!”

我正在尝试在Android上使用Mockito。我想将其与一些回调一起使用。这是我的测试:

public class LoginPresenterTest {


private User mUser = new User();

@Mock
private UsersRepository mUsersRepository;

@Mock
private LoginContract.View mLoginView;

/**
 * {@link ArgumentCaptor} is a powerful Mockito API to capture argument values and use them to
 * perform further actions or assertions on them.
 */
@Captor
private ArgumentCaptor<LoginUserCallback> mLoadLoginUserCallbackCaptor;

private LoginPresenter mLoginPresenter;

@Before
public void setupNotesPresenter() {
    // Mockito has a very convenient way to inject mocks by using the @Mock annotation. To
    // inject the mocks in the test …
Run Code Online (Sandbox Code Playgroud)

junit android junit4 mockito

2
推荐指数
1
解决办法
1066
查看次数

无法模拟android.util.Patterns.EMAIL_ADDRESS.pattern()

目前,我正在使用MockK库(版本1.8.1)在Android Dev中进行单元测试,而我的问题是我无法模拟Patterns.EMAIL_ADDRESS。每次调用此属性时,测试用例都会抛出NPE。

我尝试过mockkStatic(Patterns::class),但是@Before方法在应用规则时因NPE而崩溃every { Patterns.EMAIL_ADDRESS.pattern() } returns EMAIL_REGEX_STRING

我要测试的课程:

public class EmailValidator {

private static final String EMPTY = "";
private final Context context;

@Inject
public EmailValidator(Context context) {
    this.context = context;
}

public String isValidEmail(String email) {
    if (StringUtils.isEmpty(email)) {
        return context.getString(R.string.sign_up_error_email_empty);
    }

    if (!email.matches(Patterns.EMAIL_ADDRESS.pattern())) {
        return context.getString(R.string.sign_up_error_email_validate);
    }
    return EMPTY;
}}
Run Code Online (Sandbox Code Playgroud)

android junit4 mockk

2
推荐指数
1
解决办法
649
查看次数

SpringBootTest:没有可用的'org.springframework.test.web.servlet.MockMvc'类型的合格bean:

嘿,在创建测试用例时,我已经开始使用spring boot Test框架进行spring-boot junit测试,我面临以下问题。

    import static org.hamcrest.Matchers.containsString;
    import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
    import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
    import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
    import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.test.context.junit4.SpringRunner;
    import org.springframework.test.web.servlet.MockMvc;


    @RunWith(SpringRunner.class)
    @SpringBootTest
    @AutoConfigureMockMvc
    public class ApplicationTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void shouldReturnDefaultMessage() throws Exception {
        this.mockMvc.perform(get("/")).andDo(print()).andExpect(status().isOk())
                .andExpect(content().string(containsString("Hello World")));
    }
}
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,我遇到了错误

    Caused by: **org.springframework.beans.factory.NoSuchBeanDefinitionException: 
No qualifying bean of type 'org.springframework.test.web.servlet.MockMvc' available: 
expected at least 1 bean which qualifies as autowire candidate.
 Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}** …
Run Code Online (Sandbox Code Playgroud)

junit4 spring-boot mockmvc spring-boot-test

2
推荐指数
3
解决办法
5689
查看次数

我们是否有任何拇指规则来估计JUnit测试用例的工作日

我们有一个10年的项目,拥有1000多万行java代码.现在由于某些原因,组织决定为旧代码编写JUnit测试用例.我们正在使用Mockito JUnit测试用例.作为这一变化的一部分,我们必须估算人日工作量.它很难估计现有代码,而且我是该项目的新手.只是想知道是否有基于代码行数估计的拇指规则.

junit junit4 mockito junit5

2
推荐指数
1
解决办法
617
查看次数

标签 统计

junit4 ×10

java ×5

junit ×5

mockito ×3

android ×2

junit5 ×1

mockk ×1

mockmvc ×1

spring-boot ×1

spring-boot-test ×1