1. junit test like below
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"/spring/test-mongo-setup.xml"})
public class AlarmLogDataHandlerTest extends AbstractDbDataTest {
@Autowired
private AlarmRepository alarmRepository;
@Autowired
private AlarmDetailsRepository alarmDetailsRepository;
private AlarmErrorDataHandler handler;
private String inverterId = "inverter1";
@Before
public void init() {
setCurrentMillisSystem();
handler = new AlarmErrorDataHandler();
ReflectionTestUtils.setField(handler, "alarmRepository", alarmRepository);
}
@After
public void cleanData() {
setCurrentMillisSystem();
alarmRepository.deleteAll();
alarmDetailsRepository.deleteAll();
}
@Test
public void whenAlarmIsNewThenSaveAlarmLogsAndAlarmDetails() {
// given
String errorType = ErrorCode.L1.getErrorType();
int errorCodeL1_value1 = 2;
AlarmLogs logs = buildFullAlarmLogs(errorType, errorCodeL1_value1);
// when
handler.saveAlarmLogs(logs);
// then
Iterable<AlarmLogs> logsList = alarmRepository.findAll();
assertThat(logsList.iterator().hasNext(), equalTo(true));
AlarmLogs dbLogs = logsList.iterator().next();
assertThat(dbLogs.getVersion(), equalTo(0L));
assertThat(dbLogs.getErrorType(), equalTo(errorType));
assertThat(dbLogs.getErrorValue(), equalTo(errorCodeL1_value1));
assertThat(dbLogs.getAlarmDetails(), notNullValue());
Iterable<AlarmDetails> alarmDetails = alarmDetailsRepository.findAll();
assertThat(Lists.newArrayList(alarmDetails), hasSize(1));
}
}
2 xml configuration
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xsi:schemaLocation="http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo-1.3.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<mongo:auditing/>
<bean name="fongo" class="com.github.fakemongo.Fongo">
<constructor-arg value="InMemoryMongo"/>
</bean>
<bean id="mongo" factory-bean="fongo" factory-method="getMongo"/>
<mongo:db-factory id="mongoDbFactory" mongo-ref="mongo"/>
<!-- localhost settings for mongo -->
<!--<mongo:db-factory id="mongoDbFactory" /> -->
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg ref="mongoDbFactory"/>
</bean>
<mongo:repositories base-package="com.eifesun.monitor.web.repository" repository-impl-postfix="CustomImpl"/>
<bean class="com.eifesun.monitor.web.model.mongodb.CascadingMongoEventListener" />
</beans>
notice that: we use "com.github.fakemongo.Fongo", and "InMemoryMongo" for test.