如何将模拟注入到比测试类低两步的方法中



我想编写一种类和它在操作过程中调用的"较低"类的集成测试。我想模拟由"较低"类调用的数据库连接,但我还没有找到执行此操作的方法。

我有一个类,它调用另一个类,通过 jdbcTemplate 调用数据库。我想向下层类注入一个模拟 jdbcTemplate,但我似乎将其注入到该类的错误实例中。代码遵循以下模板:

@Component
public class A {
    @AutoWired
    B b
    public String someMethod() {
        b.otherMethod();
    }
}

@Component
public class B {
    @AutoWired
    jdbcTemplate jdbctemplate
    public String otherMethod() {
        jdbctemplate.query(args);
    }
}

测试如下:

@RunWith(MockitoJUnitRunner.Silent.class)
public class aTestClass { 
    @Mock
    JdbcTemplate jdbcTemplate;
    @InjectMocks
    B b;
    @InjectMocks
    A a;
    @Test
    public void aTest() {
        a.someMethod();
    }
}

但是当我运行这个测试时,我在 a.someMethod(( 上得到一个 NullPointerException - 似乎被调用的 B 对象是空的。

问题是,如果我模拟B,那么它永远不会真正调用jdbcTemplate,因为它是一个模拟。

谁能阐明我如何将模拟 jdbcTemplate 注入到 A 调用的 B 对象?

如果你想要一个实际的集成测试:

1(不要嘲笑模板。模拟整个存储库。

2( 在集成测试中不需要@InjectMocks。春天做DI。

3(由于这是IT测试,因此您需要使用SpringRunner.class,而不是MockitoJUnitRunner.class运行器。

@RunWith(SpringRunner.class)
public class aTestClass { 
    @MockBean
    B b;
    @Autowired
    A a;
    @Test
    public void aTest() {
        a.someMethod();
    }
}

对于单元测试,只需模拟 B 并在 A 上注入:

@RunWith(MockitoJUnitRunner.Silent.class)
public class aTestClass { 
    @Mock
    B b;
    @InjectMocks
    A a;
    @Test
    public void aTest() {
        a.someMethod();
    }
}

不要在单元测试中模拟依赖项的依赖项。你不应该关心那里的较低水平。

在 DuckDuckGo 之后,我设法让测试与 Maciejs 指令一起工作。起初它不起作用,但它确实在两个豆子中添加了@Configuration。这是对我有用的代码:

@RunWith(SpringRunner.class)
public class aTestClass { 
    @MockBean
    JdbcTemplate jdbcTemplate;
    @Autowired
    B b;
    @Autowired
    A a;
    @Test
    public void aTest() {
        when(jdbcTemplate.query(args)).thenAnswer(whatyouwant));
        a.someMethod();
    }
    @Configuration
    @Import(A.class)
    static class AConfig {
    }
    @Configuration
    @Import(B.class)
    static class BConfig {
    }
}

最新更新