mockito/spring:只模拟autowired服务中的一个函数

polhcujo  于 2021-07-24  发布在  Java
关注(0)|答案(3)|浏览(459)

我只想在真正的服务上模拟一个函数,这是通过@autowired(集成测试)注入的)->

@SpringBootTest(classes = OrderitBackendApp.class)
@ExtendWith(MockitoExtension.class)
@AutoConfigureMockMvc
@WithUserDetails
public class OrderResourceIT {

    @Autowired
    private OrderRepository orderRepository;

    ...mor Injections and Tests

这里是模拟功能->

@BeforeEach
    public void initTest() {
        MockitoAnnotations.initMocks(this);
        order = createEntity(em);
        OrderService spy = spy(orderService);
        when(spy.priceIsIncorrect(any())).thenReturn(false);
    }

但是这个和其他一些我尝试过的东西都不起作用。正确的方法是什么?

qlfbtfca

qlfbtfca1#

如果您正在使用mockito,请尝试使用@injectmocks和@mock注解。看下面的例子https://www.springboottutorial.com/spring-boot-unit-testing-and-mocking-with-mockito-and-junit

i2byvkas

i2byvkas2#

假设我们有一个有两种方法的类

public class OrderService {

    public String priceIsIncorrect(){
        return "price";
    }

    public String someOtherMethod(){
        return "other price";
    }
}

以下测试类将模拟一个方法并使用第二个方法的实际实现:

public class SomeRandomTest {
    private OrderService orderService = new OrderService();
    @Test
    public void test(){
        OrderService spy = Mockito.spy(orderService);
        Mockito.when(spy.priceIsIncorrect()).thenReturn("Spied method");
        System.out.println(spy.priceIsIncorrect()); //will return "Spied method"
        System.out.println(spy.someOtherMethod()); //will return "other price"

    }
}
jchrr9hc

jchrr9hc3#

我缺少的是将orderservice注入到被测系统(sut)的关键点。
所以有两种选择:
使用反射设置 OrderService sut的间谍示例
我认为最好的办法是尝试 @SpyBean 在你的 OrderService afair允许间谍在应用程序上下文中使用的示例。试试看。我以后需要研究这些文件。也许我错了。
进一步:在您的应用程序中,order服务在哪里被调用?对我来说,这是不清楚的基础上提供的代码。

相关问题