How to test for exception in Nest?










2














I am trying to test for the results of certain exceptions when Nest has a value in IGetResponse.OriginalException property.



I first set up the response:



var response = A.Fake<Nest.IGetResponse<Dictionary<string, object>>>();
A.CallTo(() => response.OriginalException).Returns(new Exception("Status code 404"));


Then the fake elastic client:



var client = A.Fake<Nest.IElasticClient>();
A.CallTo(client)
.WithReturnType<Nest.IGetResponse<Dictionary<string, object>>>()
.Returns(response);


The client gets injected into the class I am testing.



However, when stepping through the code, when the client is called it returns a faked response, but the OriginalException getter has no value. Its not null, but none of the properties has any value. I was expecting the OriginalException.Message to equal Status code 404.



I also tried setting the response object to:



var response = A.Fake<Nest.IGetResponse<Dictionary<string, object>>>();
A.CallTo(() => response.OriginalException.Message).Returns("Status code 404");


... with equally poor results.



How can I set the IGetResponse so I can evaluate OriginalException.Message in the class being tested?



More code was requested. I can show the entire test, and I will show the method being tested. Here is my entire test:



 [TestMethod]
[ExpectedException(typeof(NotFoundException))]
public void Get_ClientReturns404_ThrowsNotFoundException()

// setup
var request = new DataGetRequest

CollectionName = string.Empty,
DocumentType = string.Empty,
DataAccessType = string.Empty
;

var response = A.Fake<Nest.IGetResponse<Dictionary<string, object>>>();
A.CallTo(() => response.OriginalException.Message).Returns("Status code 404");

var client = A.Fake<Nest.IElasticClient>();
A.CallTo(client)
.WithReturnType<Nest.IGetResponse<Dictionary<string, object>>>()
.Returns(response);

var elasticSearch = new ElasticSearch(null, client);

// test
var result = elasticSearch.Get(request);

// assert
Assert.Fail("Should have hit an exception.");

}


And here is the method being tested:



 public async Task<Dictionary<string, object>> Get(DataGetRequest getRequest)

GetRequest request = new GetRequest(getRequest.CollectionName, getRequest.DocumentType, getRequest.Id);
var response = await Client.GetAsync<Dictionary<string, object>>(request);

if (response.OriginalException != null)

var message = response.OriginalException.Message;
if (message.Contains("Status code 404"))
throw new NotFoundException(String.Format("Not Found for id 0", getRequest.Id));
else
throw new Exception(message);


return response.Source;



The error handling in the IF block is not very robust. Once the unit test works then the code will likely receive more love.










share|improve this question























  • Nothing's popping out at me. Are you able to paste more code? Ideally a runnable test, but at least how you inject the client into the class you're testing, how you call that class, and what the called method does?
    – Blair Conrad
    Nov 9 at 20:25










  • @BlairConrad Done. Not sure how much help it will be, but you never know.
    – Sailing Judo
    Nov 9 at 20:33















2














I am trying to test for the results of certain exceptions when Nest has a value in IGetResponse.OriginalException property.



I first set up the response:



var response = A.Fake<Nest.IGetResponse<Dictionary<string, object>>>();
A.CallTo(() => response.OriginalException).Returns(new Exception("Status code 404"));


Then the fake elastic client:



var client = A.Fake<Nest.IElasticClient>();
A.CallTo(client)
.WithReturnType<Nest.IGetResponse<Dictionary<string, object>>>()
.Returns(response);


The client gets injected into the class I am testing.



However, when stepping through the code, when the client is called it returns a faked response, but the OriginalException getter has no value. Its not null, but none of the properties has any value. I was expecting the OriginalException.Message to equal Status code 404.



I also tried setting the response object to:



var response = A.Fake<Nest.IGetResponse<Dictionary<string, object>>>();
A.CallTo(() => response.OriginalException.Message).Returns("Status code 404");


... with equally poor results.



How can I set the IGetResponse so I can evaluate OriginalException.Message in the class being tested?



More code was requested. I can show the entire test, and I will show the method being tested. Here is my entire test:



 [TestMethod]
[ExpectedException(typeof(NotFoundException))]
public void Get_ClientReturns404_ThrowsNotFoundException()

// setup
var request = new DataGetRequest

CollectionName = string.Empty,
DocumentType = string.Empty,
DataAccessType = string.Empty
;

var response = A.Fake<Nest.IGetResponse<Dictionary<string, object>>>();
A.CallTo(() => response.OriginalException.Message).Returns("Status code 404");

var client = A.Fake<Nest.IElasticClient>();
A.CallTo(client)
.WithReturnType<Nest.IGetResponse<Dictionary<string, object>>>()
.Returns(response);

var elasticSearch = new ElasticSearch(null, client);

// test
var result = elasticSearch.Get(request);

// assert
Assert.Fail("Should have hit an exception.");

}


And here is the method being tested:



 public async Task<Dictionary<string, object>> Get(DataGetRequest getRequest)

GetRequest request = new GetRequest(getRequest.CollectionName, getRequest.DocumentType, getRequest.Id);
var response = await Client.GetAsync<Dictionary<string, object>>(request);

if (response.OriginalException != null)

var message = response.OriginalException.Message;
if (message.Contains("Status code 404"))
throw new NotFoundException(String.Format("Not Found for id 0", getRequest.Id));
else
throw new Exception(message);


return response.Source;



The error handling in the IF block is not very robust. Once the unit test works then the code will likely receive more love.










share|improve this question























  • Nothing's popping out at me. Are you able to paste more code? Ideally a runnable test, but at least how you inject the client into the class you're testing, how you call that class, and what the called method does?
    – Blair Conrad
    Nov 9 at 20:25










  • @BlairConrad Done. Not sure how much help it will be, but you never know.
    – Sailing Judo
    Nov 9 at 20:33













2












2








2


0





I am trying to test for the results of certain exceptions when Nest has a value in IGetResponse.OriginalException property.



I first set up the response:



var response = A.Fake<Nest.IGetResponse<Dictionary<string, object>>>();
A.CallTo(() => response.OriginalException).Returns(new Exception("Status code 404"));


Then the fake elastic client:



var client = A.Fake<Nest.IElasticClient>();
A.CallTo(client)
.WithReturnType<Nest.IGetResponse<Dictionary<string, object>>>()
.Returns(response);


The client gets injected into the class I am testing.



However, when stepping through the code, when the client is called it returns a faked response, but the OriginalException getter has no value. Its not null, but none of the properties has any value. I was expecting the OriginalException.Message to equal Status code 404.



I also tried setting the response object to:



var response = A.Fake<Nest.IGetResponse<Dictionary<string, object>>>();
A.CallTo(() => response.OriginalException.Message).Returns("Status code 404");


... with equally poor results.



How can I set the IGetResponse so I can evaluate OriginalException.Message in the class being tested?



More code was requested. I can show the entire test, and I will show the method being tested. Here is my entire test:



 [TestMethod]
[ExpectedException(typeof(NotFoundException))]
public void Get_ClientReturns404_ThrowsNotFoundException()

// setup
var request = new DataGetRequest

CollectionName = string.Empty,
DocumentType = string.Empty,
DataAccessType = string.Empty
;

var response = A.Fake<Nest.IGetResponse<Dictionary<string, object>>>();
A.CallTo(() => response.OriginalException.Message).Returns("Status code 404");

var client = A.Fake<Nest.IElasticClient>();
A.CallTo(client)
.WithReturnType<Nest.IGetResponse<Dictionary<string, object>>>()
.Returns(response);

var elasticSearch = new ElasticSearch(null, client);

// test
var result = elasticSearch.Get(request);

// assert
Assert.Fail("Should have hit an exception.");

}


And here is the method being tested:



 public async Task<Dictionary<string, object>> Get(DataGetRequest getRequest)

GetRequest request = new GetRequest(getRequest.CollectionName, getRequest.DocumentType, getRequest.Id);
var response = await Client.GetAsync<Dictionary<string, object>>(request);

if (response.OriginalException != null)

var message = response.OriginalException.Message;
if (message.Contains("Status code 404"))
throw new NotFoundException(String.Format("Not Found for id 0", getRequest.Id));
else
throw new Exception(message);


return response.Source;



The error handling in the IF block is not very robust. Once the unit test works then the code will likely receive more love.










share|improve this question















I am trying to test for the results of certain exceptions when Nest has a value in IGetResponse.OriginalException property.



I first set up the response:



var response = A.Fake<Nest.IGetResponse<Dictionary<string, object>>>();
A.CallTo(() => response.OriginalException).Returns(new Exception("Status code 404"));


Then the fake elastic client:



var client = A.Fake<Nest.IElasticClient>();
A.CallTo(client)
.WithReturnType<Nest.IGetResponse<Dictionary<string, object>>>()
.Returns(response);


The client gets injected into the class I am testing.



However, when stepping through the code, when the client is called it returns a faked response, but the OriginalException getter has no value. Its not null, but none of the properties has any value. I was expecting the OriginalException.Message to equal Status code 404.



I also tried setting the response object to:



var response = A.Fake<Nest.IGetResponse<Dictionary<string, object>>>();
A.CallTo(() => response.OriginalException.Message).Returns("Status code 404");


... with equally poor results.



How can I set the IGetResponse so I can evaluate OriginalException.Message in the class being tested?



More code was requested. I can show the entire test, and I will show the method being tested. Here is my entire test:



 [TestMethod]
[ExpectedException(typeof(NotFoundException))]
public void Get_ClientReturns404_ThrowsNotFoundException()

// setup
var request = new DataGetRequest

CollectionName = string.Empty,
DocumentType = string.Empty,
DataAccessType = string.Empty
;

var response = A.Fake<Nest.IGetResponse<Dictionary<string, object>>>();
A.CallTo(() => response.OriginalException.Message).Returns("Status code 404");

var client = A.Fake<Nest.IElasticClient>();
A.CallTo(client)
.WithReturnType<Nest.IGetResponse<Dictionary<string, object>>>()
.Returns(response);

var elasticSearch = new ElasticSearch(null, client);

// test
var result = elasticSearch.Get(request);

// assert
Assert.Fail("Should have hit an exception.");

}


And here is the method being tested:



 public async Task<Dictionary<string, object>> Get(DataGetRequest getRequest)

GetRequest request = new GetRequest(getRequest.CollectionName, getRequest.DocumentType, getRequest.Id);
var response = await Client.GetAsync<Dictionary<string, object>>(request);

if (response.OriginalException != null)

var message = response.OriginalException.Message;
if (message.Contains("Status code 404"))
throw new NotFoundException(String.Format("Not Found for id 0", getRequest.Id));
else
throw new Exception(message);


return response.Source;



The error handling in the IF block is not very robust. Once the unit test works then the code will likely receive more love.







c# mstest nest fakeiteasy






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 9 at 20:31

























asked Nov 9 at 19:40









Sailing Judo

6,632125588




6,632125588











  • Nothing's popping out at me. Are you able to paste more code? Ideally a runnable test, but at least how you inject the client into the class you're testing, how you call that class, and what the called method does?
    – Blair Conrad
    Nov 9 at 20:25










  • @BlairConrad Done. Not sure how much help it will be, but you never know.
    – Sailing Judo
    Nov 9 at 20:33
















  • Nothing's popping out at me. Are you able to paste more code? Ideally a runnable test, but at least how you inject the client into the class you're testing, how you call that class, and what the called method does?
    – Blair Conrad
    Nov 9 at 20:25










  • @BlairConrad Done. Not sure how much help it will be, but you never know.
    – Sailing Judo
    Nov 9 at 20:33















Nothing's popping out at me. Are you able to paste more code? Ideally a runnable test, but at least how you inject the client into the class you're testing, how you call that class, and what the called method does?
– Blair Conrad
Nov 9 at 20:25




Nothing's popping out at me. Are you able to paste more code? Ideally a runnable test, but at least how you inject the client into the class you're testing, how you call that class, and what the called method does?
– Blair Conrad
Nov 9 at 20:25












@BlairConrad Done. Not sure how much help it will be, but you never know.
– Sailing Judo
Nov 9 at 20:33




@BlairConrad Done. Not sure how much help it will be, but you never know.
– Sailing Judo
Nov 9 at 20:33












1 Answer
1






active

oldest

votes


















2














The return type of the mocked client is wrong as the IElasticClient.GetAsync<> returns a Task<IGetResponse<T>>.



Task<IGetResponse<T>> GetAsync<T>(IGetRequest request, CancellationToken cancellationToken = default(CancellationToken)) where T : class;


Source



So the setup needs to return a Task derived result to allow the async code



var response = await Client.GetAsync<Dictionary<string, object>>(request);


to flow as expected.



For example



[TestMethod]
[ExpectedException(typeof(NotFoundException))]
public async Task Get_ClientReturns404_ThrowsNotFoundException()

//Arrange
var originalException = new Exception("Status code 404");

var response = A.Fake<Nest.IGetResponse<Dictionary<string, object>>>();
A.CallTo(() => response.OriginalException).Returns(originalException);

var client = A.Fake<Nest.IElasticClient>();
A.CallTo(() =>
client.GetAsync<Dictionary<string, object>>(A<IGetRequest>._, A<CancellationToken>._)
).Returns(Task.FromResult(response));

var request = new DataGetRequest
CollectionName = string.Empty,
DocumentType = string.Empty,
DataAccessType = string.Empty
;

var elasticSearch = new ElasticSearch(null, client);

// Act
var result = await elasticSearch.Get(request);

// Assert
Assert.Fail("Should have hit an exception.");






share|improve this answer


















  • 1




    Nice. And a bonus +1 for faking GetAsync directly rather than using the powerful, but potentially error-prone, WithReturnType syntax.
    – Blair Conrad
    Nov 10 at 17:31










Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53232285%2fhow-to-test-for-exception-in-nest%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









2














The return type of the mocked client is wrong as the IElasticClient.GetAsync<> returns a Task<IGetResponse<T>>.



Task<IGetResponse<T>> GetAsync<T>(IGetRequest request, CancellationToken cancellationToken = default(CancellationToken)) where T : class;


Source



So the setup needs to return a Task derived result to allow the async code



var response = await Client.GetAsync<Dictionary<string, object>>(request);


to flow as expected.



For example



[TestMethod]
[ExpectedException(typeof(NotFoundException))]
public async Task Get_ClientReturns404_ThrowsNotFoundException()

//Arrange
var originalException = new Exception("Status code 404");

var response = A.Fake<Nest.IGetResponse<Dictionary<string, object>>>();
A.CallTo(() => response.OriginalException).Returns(originalException);

var client = A.Fake<Nest.IElasticClient>();
A.CallTo(() =>
client.GetAsync<Dictionary<string, object>>(A<IGetRequest>._, A<CancellationToken>._)
).Returns(Task.FromResult(response));

var request = new DataGetRequest
CollectionName = string.Empty,
DocumentType = string.Empty,
DataAccessType = string.Empty
;

var elasticSearch = new ElasticSearch(null, client);

// Act
var result = await elasticSearch.Get(request);

// Assert
Assert.Fail("Should have hit an exception.");






share|improve this answer


















  • 1




    Nice. And a bonus +1 for faking GetAsync directly rather than using the powerful, but potentially error-prone, WithReturnType syntax.
    – Blair Conrad
    Nov 10 at 17:31















2














The return type of the mocked client is wrong as the IElasticClient.GetAsync<> returns a Task<IGetResponse<T>>.



Task<IGetResponse<T>> GetAsync<T>(IGetRequest request, CancellationToken cancellationToken = default(CancellationToken)) where T : class;


Source



So the setup needs to return a Task derived result to allow the async code



var response = await Client.GetAsync<Dictionary<string, object>>(request);


to flow as expected.



For example



[TestMethod]
[ExpectedException(typeof(NotFoundException))]
public async Task Get_ClientReturns404_ThrowsNotFoundException()

//Arrange
var originalException = new Exception("Status code 404");

var response = A.Fake<Nest.IGetResponse<Dictionary<string, object>>>();
A.CallTo(() => response.OriginalException).Returns(originalException);

var client = A.Fake<Nest.IElasticClient>();
A.CallTo(() =>
client.GetAsync<Dictionary<string, object>>(A<IGetRequest>._, A<CancellationToken>._)
).Returns(Task.FromResult(response));

var request = new DataGetRequest
CollectionName = string.Empty,
DocumentType = string.Empty,
DataAccessType = string.Empty
;

var elasticSearch = new ElasticSearch(null, client);

// Act
var result = await elasticSearch.Get(request);

// Assert
Assert.Fail("Should have hit an exception.");






share|improve this answer


















  • 1




    Nice. And a bonus +1 for faking GetAsync directly rather than using the powerful, but potentially error-prone, WithReturnType syntax.
    – Blair Conrad
    Nov 10 at 17:31













2












2








2






The return type of the mocked client is wrong as the IElasticClient.GetAsync<> returns a Task<IGetResponse<T>>.



Task<IGetResponse<T>> GetAsync<T>(IGetRequest request, CancellationToken cancellationToken = default(CancellationToken)) where T : class;


Source



So the setup needs to return a Task derived result to allow the async code



var response = await Client.GetAsync<Dictionary<string, object>>(request);


to flow as expected.



For example



[TestMethod]
[ExpectedException(typeof(NotFoundException))]
public async Task Get_ClientReturns404_ThrowsNotFoundException()

//Arrange
var originalException = new Exception("Status code 404");

var response = A.Fake<Nest.IGetResponse<Dictionary<string, object>>>();
A.CallTo(() => response.OriginalException).Returns(originalException);

var client = A.Fake<Nest.IElasticClient>();
A.CallTo(() =>
client.GetAsync<Dictionary<string, object>>(A<IGetRequest>._, A<CancellationToken>._)
).Returns(Task.FromResult(response));

var request = new DataGetRequest
CollectionName = string.Empty,
DocumentType = string.Empty,
DataAccessType = string.Empty
;

var elasticSearch = new ElasticSearch(null, client);

// Act
var result = await elasticSearch.Get(request);

// Assert
Assert.Fail("Should have hit an exception.");






share|improve this answer














The return type of the mocked client is wrong as the IElasticClient.GetAsync<> returns a Task<IGetResponse<T>>.



Task<IGetResponse<T>> GetAsync<T>(IGetRequest request, CancellationToken cancellationToken = default(CancellationToken)) where T : class;


Source



So the setup needs to return a Task derived result to allow the async code



var response = await Client.GetAsync<Dictionary<string, object>>(request);


to flow as expected.



For example



[TestMethod]
[ExpectedException(typeof(NotFoundException))]
public async Task Get_ClientReturns404_ThrowsNotFoundException()

//Arrange
var originalException = new Exception("Status code 404");

var response = A.Fake<Nest.IGetResponse<Dictionary<string, object>>>();
A.CallTo(() => response.OriginalException).Returns(originalException);

var client = A.Fake<Nest.IElasticClient>();
A.CallTo(() =>
client.GetAsync<Dictionary<string, object>>(A<IGetRequest>._, A<CancellationToken>._)
).Returns(Task.FromResult(response));

var request = new DataGetRequest
CollectionName = string.Empty,
DocumentType = string.Empty,
DataAccessType = string.Empty
;

var elasticSearch = new ElasticSearch(null, client);

// Act
var result = await elasticSearch.Get(request);

// Assert
Assert.Fail("Should have hit an exception.");







share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 10 at 1:08

























answered Nov 10 at 1:02









Nkosi

109k16115183




109k16115183







  • 1




    Nice. And a bonus +1 for faking GetAsync directly rather than using the powerful, but potentially error-prone, WithReturnType syntax.
    – Blair Conrad
    Nov 10 at 17:31












  • 1




    Nice. And a bonus +1 for faking GetAsync directly rather than using the powerful, but potentially error-prone, WithReturnType syntax.
    – Blair Conrad
    Nov 10 at 17:31







1




1




Nice. And a bonus +1 for faking GetAsync directly rather than using the powerful, but potentially error-prone, WithReturnType syntax.
– Blair Conrad
Nov 10 at 17:31




Nice. And a bonus +1 for faking GetAsync directly rather than using the powerful, but potentially error-prone, WithReturnType syntax.
– Blair Conrad
Nov 10 at 17:31

















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.





Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


Please pay close attention to the following guidance:


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53232285%2fhow-to-test-for-exception-in-nest%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)