如何仅在1个否定testCase中停止在applicationContext中模拟的MongoDb?

时间:2019-04-21 13:22:08

标签: java mongodb junit

如何为应用程序的负集成测试模拟“ DB down”条件?

必须在上下文中编写具有模拟Db的应用程序的负集成测试:

CREATE TABLE [dbo].[TopicKeyword] 
(
    [Id]      SMALLINT     NOT NULL,
    [Keyword] VARCHAR(100) NOT NULL,
    [Volume]  INT          NOT NULL,
    [PageId]  SMALLINT     NOT NULL,
    CONSTRAINT [PK_TopicKeyword] PRIMARY KEY CLUSTERED ([Id] ASC)
);
GO

// New
CREATE UNIQUE NONCLUSTERED INDEX [IX_TopicKeyword_Id_PageId]
ON [dbo].[TopicKeyword]([Id] ASC, [PageId] ASC);

CREATE TABLE [dbo].[TopicCluster] 
(
    [KeywordId] SMALLINT NOT NULL,
    [PageId]    SMALLINT NOT NULL,
    CONSTRAINT [PK_TopicCluster] PRIMARY KEY CLUSTERED ([KeywordId] ASC),
    CONSTRAINT [AK_TopicCluster_PageId] UNIQUE NONCLUSTERED ([PageId] ASC), // New
    CONSTRAINT [FK_TopicCluster_TopicKeyword] FOREIGN KEY ([KeywordId]) REFERENCES [dbo].[TopicKeyword] ([Id]),
    CONSTRAINT [FK_TopicCluster_TopicKeyword2] FOREIGN KEY ([KeywordId], [PageId]) REFERENCES [dbo].[TopicKeyword] ([Id], [PageId]) // New
);
GO

// New
CREATE NONCLUSTERED INDEX [IX_TopicCluster_KeywordId_PageId]
ON [dbo]

MongoDb类为:

    @Bean
public MongoDb mongoDb() throws URISyntaxException {
        return new MongoDb(new URI(String.format("mongodb://localhost:%s/", mongoDbPort)), databaseName);
    }

如何在这里为负测试用例(具有相同的上下文bean)模拟“ DB down”条件?

尝试在我的testCase中停止mongo: mongoDb.getMongo()。dropDatabase(dbnameValue); 但没有引发任何异常

任何线索都值得赞赏!

1 个答案:

答案 0 :(得分:0)

关于将PowerMockito与MongoDB结合使用的旧文章:Unit testing with MongoDB

API发生了变化,但是模拟方式仍然可以使用。

MongoClient mongo = PowerMockito.mock(MongoClient.class);
PowerMockito.when(mongo.getDatabase("DBDownForTest")).doThrow(new MongoClientException("Test DB is down"));

仅当您使用参数getDatabase调用DBDownForTest时,此方法才有效。否则,您将不得不使用anyString()

也许您甚至可以在当前的MongoDB版本中使用不带PowerMockito的Mockito。