如何用Mockito在另一个mock类中模拟Spring消息资源



在我的测试中,当我断言异常消息时,我得到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,但我不能使用Servicemessage !!

有人能帮帮我吗?

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

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

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

相关内容

  • 没有找到相关文章

最新更新