使用GUICE,如何将单位测试中的模拟对象注入被测试的类



考虑以下代码:

@Singleton
public class MyServiceImpl {
    public int doSomething() {
        return 5;
    }
}
@ImplementedBy(MyServiceImpl.class)
public interface MyService {
    public int doSomething();
}
public class MyCommand {
    @Inject private MyService service;
    public boolean executeSomething() {
        return service.doSomething() > 0;
    }
}
public class MyCommandTest {
    @InjectMocks MyServiceImpl serviceMock;
    private MyCommand command;
    @Before public void beforeEach() {
        MockitoAnnotations.initMocks(this);
        command = new MyCommand();
        when(serviceMock.doSomething()).thenReturn(-1); // <- Error here
    }
    @Test public void mockInjected() {
        boolean result = command.executeSomething();
        verify(serviceMock).doSomething();
        assertThat(result, equalTo(false));
    }
}

当我试图将Dosomething()方法固态在我的模拟实现对象上时,我的测试正在倒塌。我有错误:

org.mockito.exceptions.misusing.missingmethodinvocation exception: 当()需要一个必须是"模拟方法的方法"的参数。 例如: 当(mock.getArticles())。

另外,此错误可能出现是因为: 1.您存根于:final/private/equals()/hashcode()方法。这些方法不能被固定/验证。模拟方法 不支持在非公共父母类上声明。 2.内部()()您不在模拟上调用方法,而是在某些其他对象上调用方法。

我是通过Guice依赖注入的新手,不确定为什么我不能以这种方式模拟实现对象?

没有CDI

测试

一个简单的解决方案是将CDI与构造函数注入结合,而忘记了测试的GUICE:

public class MyCommand {
    private final MyService service;
    @Inject
    public MyCommand(MyService service) {
        this.service = service;
    }
    public boolean executeSomething() {
        return service.doSomething() > 0;
    }
}
@RunWith(MockitoJUnitRunner.class)
public class MyCommandTest {
    @Mock
    MyServiceImpl serviceMock;
    private MyCommand command;
    @Before public void beforeEach() {
        MockitoAnnotations.initMocks(this);
        when(serviceMock.doSomething()).thenReturn(-1); // <- Error here
        // inject without Guice
        command = new MyCommand(serviceMock);
    }
}

用摩擦图进行CDI

测试

其他,如果您不喜欢构造函数注入,则测试代码应该看起来像:

@RunWith(MockitoJUnitRunner.class)
public class MyCommandTest {
    @Mock
    MyServiceImpl serviceMock;
    @InjectMocks 
    private MyCommand command;
    private AutoCloseable mockHandler;
    @Before
    public void beforeEach() {
        // initialize members annotated with @Mock and @InjectMocks
        mockHandler = MockitoAnnotations.openMocks(this);
        when(serviceMock.doSomething()).thenReturn(-1); // <- Error here
    }
    @After
    public void afterEach() throws Exception {
        mockHandler.close();
    }
}

相关内容

  • 没有找到相关文章

最新更新