Jukito Provider mock返回null

时间:2018-03-06 08:38:59

标签: java jukito

我在jukito单元测试中遇到了一些问题。我似乎无法模拟提供者。示例:

import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;

@Singleton
public class ServiceClass1 {
    @Inject
    Provider<ConnectionClass> provider;

    public void method1() {
        Object o = provider.get().getO(); //during mainTest, provider is null and I get Nullpointer
    }
}

@Singleton
public class ConnectionClass {
    public Object getO() {
        //this is not relevant
    }
}

public class ConfigurationModule extends AbstractModule {
    bind(ServiceClass1.class).in(Singleton.class);
    bind(ConnectionClass.class).in(Singleton.class);
}

@RunWith(JukitoRunner.class)
public class ServiceClass1Test {
    @InjectMocks
    ServiceClass1 service;

    @Mock
    Provider<ConnectionClass> connectionClassProvider;

    @Mock
    ConnectionClass connectionClass;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
        when(connectionClassProvider.get()).thenReturn(connectionClass); 
    }

    @Test
    public void mainTest() {
        service.method1();
    }
}

我希望得到一个模拟连接类,但是提供者返回null。我尝试将connectionClass绑定到TestSingleton,但这没有帮助。内部测试类:

public static class Module extends JukitoModule {
    @Override
    protected void configureTest() {
        bindMock(ConnectionClass.class).in(TestSingleton.class);
    }
}

如果有人对我有任何建议,我将不胜感激。

1 个答案:

答案 0 :(得分:0)

使用构造函数注入而不是字段注入:

@Singleton
public class ServiceClass1 {

    Provider<ConnectionClass> provider;

    @Inject
    public ServiceClass1(Provider<ConnectionClass> provider) {
        this.provider = provider;
    }
}

并删除InjectMocks:

@Mock
Provider<ConnectionClass> provider;

ServiceClass1 serviceClass1;

@Before
public void setup() {
    MockitoAnnotations.initMocks(this);
    serviceClass1 = new ServiceClass1(provider);
}

让一切顺利。 InjectMocks能成为原因吗?无论如何,我想现在这样做。