Mockito 测试用例在模拟方法时不起作用

Mockito Test case not working when mocking a method

我在下面创建了一个示例来测试 Mockito 是否能够模拟该方法和 return 我的值,但它不起作用。这是 classes.

package com.te;

public interface IA {
Long getVal(Long v);
}
package com.te;

public class A implements IA{

@Override
public Long getVal(Long v) {
    return 1L;
}


package com.te;

public class AService {

public void ser(){
    A a = new A();
    boolean d = a.getVal(1L) > 0;
    if(d){
        System.out.println("Inside If");
    }
}}

import com.te.A;
import com.te.AService;
import com.te.IA;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;

@RunWith(MockitoJUnitRunner.class)
public class ATest {

@Test
public void test(){
    IA a = Mockito.mock(A.class);
    AService s = new AService();
    Mockito.when(a.getVal(1l)).thenReturn(0L);
    s.ser();
}}

在我的测试中 class 我正在模拟方法并要求它 return 0 但它仍然是 returns 1 从方法。我不确定为什么它不起作用,我尝试搜索但找不到任何东西。请帮助我了解我在这里不正确的地方。谢谢

我想问题是你在方法 ser.取而代之的是,尝试将其作为参数并在外部创建。 在测试中,您首先像现在一样创建模拟,定义其行为,然后将其作为参数传递给 ser 方法。


    public class AService 
    { IA a = new A(); 

    public void ser(IA a){ 
    boolean d = a.getVal(1L) > 0; 
    if(d){ 
    System.out.println("Inside If"); 
    }}
</pre>
		

它不起作用的原因是您使用 IA a = Mockito.mock(A.class); 创建的 IA 实例与 ser 方法正在使用的实例不同。

每次调用 ser 时,它都会创建自己的新 IA 实例,但不会使用模拟实例。

要使 类 可测试,最好注入依赖项而不是在代码中使用 new 关键字创建它们。

package com.te;

public class AService {
private IA a;
public AService(IA a) {
 this.a = a;
}

public void ser(){
    boolean d = a.getVal(1L) > 0;
    if(d){
        System.out.println("Inside If");
    }
}}

测试

@Test
public void test(){
    IA a = Mockito.mock(A.class);
    AService s = new AService(a);
    Mockito.when(a.getVal(1l)).thenReturn(0L);
    s.ser();
}}