Java 如何测试内部调用不同方法的方法?
我在服务类中有一个名为Java 如何测试内部调用不同方法的方法?,java,unit-testing,junit,easymock,Java,Unit Testing,Junit,Easymock,我在服务类中有一个名为addSong(song,userId)的单元测试方法。我从Dao类调用了其中的三个方法。我正在使用easymock来模拟dao类。在设置中,我首先模拟我在addSong(song,userId)中调用的所有方法,然后调用service.addSong(song,userId)方法进行测试 但我得到了以下错误: Java.lang.IllegalStateException: missing behavior definition for the preceding met
addSong(song,userId)
的单元测试方法。我从Dao类
调用了其中的三个方法。我正在使用easymock来模拟dao类
。在设置中,我首先模拟我在addSong(song,userId)
中调用的所有方法,然后调用service.addSong(song,userId)
方法进行测试
但我得到了以下错误:
Java.lang.IllegalStateException: missing behavior definition for the preceding method call:
MusicPlayerDao.addSong(song)
Usage is: expect(a.foo()).andXXX()
at org.easymock.internal.MockInvocationHandler.invoke(MockInvocationHandler.java:42)
at org.easymock.internal.ObjectMethodsFilter.invoke(ObjectMethodsFilter.java:94)
at org.easymock.internal.ClassProxyFactory$MockMethodInterceptor.intercept(ClassProxyFactory.java:97)
at service.MusicPlayerDao$$EnhancerByCGLIB$$45bc3ca1.addSong(<generated>)
at service.MusicPlayerServiceImpl.addSong(MusicPlayerServiceImpl.java:43)
at AddSongTest.addSongs(AddSongTest.java:90)
服务类中的My addSong方法:
public boolean addSong(Song song, int userId) throws Exception {
MusicPlayerDaoInterface musicPlayerDao = MusicPlayerDao.getInstance();
boolean status = false;
int songId = 0;
TransactionManager transactionManager = TransactionManagerImpl
.getInstance();
try {
if (song != null) {
if (song.getTitle() != null) {
transactionManager.begin();
songId = musicPlayerDao.addSong(song);
song.setSongId(songId);
if (song.getGenre() != null
&& song.getGenre().getGenreName() != null) {
musicPlayerDao.addGenre(song.getGenre(),
song.getSongId());
}
if (song.getAlbum() != null
&& song.getAlbum().getAlbumName() != null) {
musicPlayerDao.addAlbum(song.getAlbum(),
song.getSongId());
}
if (userId != 0 && songId != 0) {
musicPlayerDao.userIdSongsMapping(userId,
song.getSongId());
}
transactionManager.commit();
status = true;
}
}
} catch (SQLException | RollbackException | HeuristicMixedException
| HeuristicRollbackException e) {
transactionManager.rollback();
status = false;
throw e;
}
return status;
}
我不知道我是不是做错了。请提供帮助。尝试从
addSongs
测试用例中删除以下行:
this.album = new Album();
album.setAlbumName("album");
this.genre = new Genre();
genre.setGenreName("genre");
this.song = new Song("song",this.album,3,"artist","composer",this.genre);
我假设在addSongs之前调用了addSongSetup
(例如;@before
)。您在addSong
中将值重新分配给变量album、genre和song,我认为EasyMock无法与addSongSetup
as中的模拟设置相匹配(取决于EasyMock如何实现这一点)
我猜是1。我认为您缺少了一个
EasyMock.replay
语句,请在您记录预期的行为后重新播放。差不多
EasyMock.replay(this.dao);
从:
要获得模拟对象,我们需要
您能添加歌曲(genr和Album)的实现吗?您是否在这些类中实现了equals和hashcode?
EasyMock.replay(this.dao);