在我的测试中,当我断言异常消息时,我得到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
,但我不能使用Service
的message
!!
有人能帮帮我吗?
在不了解Message
接口的情况下很难确定,但是很容易发现您将模拟对象配置为带有签名getMessage(String, List)
的stub方法:
when(message.getMessage(eq(REQUIRED_FIELD), any(List.class))).thenReturn(REQUIRED_FIELD);
但是,ServiceImpl
使用getMessage(String, String)
。在这种情况下,mock返回的默认值是null
。您必须正确配置mock对象。