繁体   English   中英

使用Mockito设置单元测试

[英]Setting up an unit test with Mockito

我正在尝试使用Mockito为注射建立一个简单的单元测试。 这个项目只是概念验证,是我朋友为他的项目进行的测试。

我遇到的问题是,我从调用的方法而不是“ Hello World”中得到null。 同样,当我调试时,我进入一个名为MethodInterceptorFilter的类,该类使用IndexOutOfBoundsExpetion作为其参数之一来调用方法intercept

有人知道我在做什么错吗?

DAO:

@Stateless
public interface DAO {
     public String helloWorld();
}

DAO实施:

@Stateless
public class DAOImpl implements DAO{

    public String helloWorld() {
        return "Hello World";
    }
}

服务:

@Stateless
public class Service {
    @Inject
    private DAO dao;

    public String helloWorld() {
        return dao.helloWorld();
    }
}

测试:

public class RandomTest {

    @InjectMocks
    Service service = new Service();

    @Mock
    DAO dao;

    @Before
    public void init(){
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void testTest() {
        assertEquals("Hello World", service.helloWorld());
    }
}

顺便说一句,我正在使用IntelliJ(不知道这是否重要,但无论如何要说)。

首先, '@InjectMocks'创建该类的实例,并注入带有'@Mock' (或'@Spy' )注释'@Spy' ,因此尝试删除@Before方法,或手动注入但删除@InjectMocks批注。

其次, '@Mock'类是扩展您的类并且不实现任何方法的类(返回null ),以便为需要对它进行存根的方法配置行为

when(...).thenReturn()

或者如果使用BDD

given(...).willReturn()

如果要使用void方法,请尝试使用'@Spy' ,最后,如果将Mockito用作JUnit测试运行程序,则需要在Test类上使用运行程序'@RunWith(MockitoJUnitRunner.class)'批注(这是默认设置)跑步者)对Mockito一无所知。

DAO类在您的Service类中被模拟,您需要指定要模拟的返回对象。

@Test
public void testTest() {
    when(dao.helloWorld()).thenReturn("Hello World")
    assertEquals("Hello World", service.helloWorld());
}

或者您可以使用构造注入:

@Stateless
public class Service {

    private DAO dao;

    @Inject
    public Service(DAO dao) {
       this.dao = dao;        
    }

    public String helloWorld() {
        return dao.helloWorld();
    }
}

public class RandomTest {

    Service service;

    @Before
    public void init(){
        service = new Service(new DAOImpl());
    }

    @Test
    public void testTest() {
        assertEquals("Hello World", service.helloWorld());
    }
}

还是反射,例如在Spring中,有一个实用程序类http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/test/util/ReflectionTestUtils.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM