java - 如何使用 Mockito 在另一个 Mock 类中模拟 Spring 消息资源?

标签 java spring unit-testing mockito

在我的测试中,当我断言异常消息时,我得到 null

我没有 mock 服务中的消息......:(

我有:

我的测试:

@RunWith(MockitoJUnitRunner.class)
public class ServiceImplTest {

    @InjectMocks
    private ServiceImpl service;

    @Mock
    private Message message;

    public static final String REQUIRED_FIELD = "required.field";

    @Before
    public void setUp() {
        when(message.getMessage(eq(REQUIRED_FIELD), any(List.class))).thenReturn(REQUIRED_FIELD);

        System.out.println(message.getMessage(REQUIRED_FIELD, new ArrayList()));
    }

    @Test(expected = MyException.class)
    public void testCancel_shouldValidCancellation_and_ThrowTicketException_with_RequiredFieldMessage() {
        try {
            Object object = //... new object
            service.do(object);
        } catch (Exception e) {
            assertEquals(REQUIRED_FIELD, e.getMessage()); // <-- e.getMessage return null!!!
        }
    }
}

我的服务:

@Service
public class ServiceImpl implements Service {

    @Autowired
    Message message;

    @Override
    public Object do(Object object) {
        if(object.getSomeAttribute() == null)) {
            throw new MyException(message.getMessage("required.field", "attribute"));
        }

        //doSomething...
        return something;
    }
}

在测试的 setUp() 中,printLn() 打印 required.field 但我无法使用 message<服务!!

有人可以帮助我吗?

最佳答案

如果不了解 Message 的接口(interface),很难确定,但很容易发现您将模拟对象配置为带有签名 getMessage(String, List) 的 stub 方法:

when(message.getMessage(eq(REQUIRED_FIELD), any(List.class))).thenReturn(REQUIRED_FIELD);

但是,ServiceImpl 使用getMessage(String, String)。在这种情况下,mock 返回的默认值为 null。您必须正确配置模拟对象。

关于java - 如何使用 Mockito 在另一个 Mock 类中模拟 Spring 消息资源?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40130120/

相关文章:

java - HttpServerErrorException 是否可以返回 HttpStatus 类中枚举器指定的代码以外的 HttpStatus 代码?

Java - Spring AOP 切入点不起作用

php - 如何在 PHP 中对具有依赖关系的方法进行单元测试?

javascript - spy 单元测试失败。说 spy 从未被称为

java - SWT:如何找到选择的项目?

java - 右键单击在 NetBeans 8.0.2 中不起作用

Java `InvocationTargetException` 通过反射进行类实例化

eclipse - STS Upgrate 导致 MatchLocator 问题

java - 您可以创建(Oracle JVM)java 堆的最小值是多少?

unit-testing - 无法使用 maven 运行单个测试方法